我写了一个程序,让我添加类别,因为它在第一个位置有一些特殊字符和数字的问题,所以我制作了一个正则过滤器,这只能照顾人物。但是,如果我使用现在包含一个数字的单词,则该方法也出于某种原因返回true。
private boolean containsSpecChar () {
Pattern pattern = Pattern.compile("[a-zA-Z0-9]");
Pattern p = Pattern.compile("[0-9a-zA-Z]");
String a = null;
a = txtInKategorieName.getText();
Matcher match= pattern.matcher(a);
Matcher m = p.matcher(a);
if (
match.matches() || m.matches()
)
{
return false;
}
else
{
return true;
}
}
我也希望能够使用包含数字的单词。谢谢
[a-zA-Z0-9]
和 [0-9a-zA-Z]
是同一件事。
[xxx]
REGEX模式是字符类,它匹配A single 字符。如果要匹配这些字符的一个或多个,则需要在结尾添加+
量词:
"[a-zA-Z0-9]+"
如果您只想为包含字母和数字的单词true使用[a-zA-Z0-9]+
作为模式。
这是.matches
方法:
public static boolean containsSpecChar () {
Pattern pattern = Pattern.compile("[a-zA-Z0-9]+");
String a = txtInKategorieName.getText();
Matcher match = pattern.matcher(a);
return !match.matches();
}
这是.find
的方式:
public static boolean containsSpecChar () {
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
String a = txtInKategorieName.getText();
Matcher match = pattern.matcher(a);
return match.find();
}