Java中正则表达式判断

来源:百度知道 编辑:UC知道 时间:2024/07/01 06:57:15
String name = txtname.getText();
if ("".equals(name))
{
JOptionPane.showMessageDialog(this, "用户名不能为空", "提示",JOptionPane.INFORMATION_MESSAGE);
}
name试文本框里面取出来的值.我要判断name不能以数字和非法字符怎么写正则表达式.
if (name.matches("^\\w+$")) 数字和英文都可以进入if里面 我要的是name只能是字母和字
if (name.matches("^\\w+$"))
{
JOptionPane.showMessageDialog(this, "用户名不合法", "提示",
JOptionPane.INFORMATION_MESSAGE);
请问有不有JAVA群可以问啊.每次上知道都要登答案

查查正则所代表的含义不就自己能写了吗?
非数字 \D
附:

\d 等於 [0-9] 数字
\D 等於 [^0-9] 非数字
\s 等於 [ \t\n\x0B\f\r] 空白字元
\S 等於 [^ \t\n\x0B\f\r] 非空白字元
\w 等於 [a-zA-Z_0-9] 数字或是英文字
\W 等於 [^a-zA-Z_0-9] 非数字与英文字

^ 表示每行的开头
$ 表示每行的结尾
----------------------
一楼的是对的。String.matches返回boolean值。
if (name.matches("^\\w+$")) {
...
}
注意转义字符。

import java.util.regex.*;

String name = txtname.getText();
try {
if (name.matches("[a-zA-Z]+")) {
// String matched entirely
} else {
// Match attempt failed
}
} catch (PatternSyntaxException ex) {
JOptionPane.showMessageDialog(this, "用户名不能为空", "提示",JOptionPane.INFORMATION_MESSAGE);
// Syntax error in the regular expression
}

/^[a-zA-Z]$/