Java正则表达式检查特殊字符总是返回true



无论我通过这个函数传递什么,一切都是真的。

asd -> should be false
asd123 -> should be false
asd 123 -> should be false
asd_123 -> should be false
asd-123 -> should be false
asd asd -> should be false

任何其他特殊字符都应返回true。

public static boolean checkSpecialChars(String word) {
Pattern pattern = Pattern.compile("[a-zA-Z0-9 -_]+", Pattern.MULTILINE);
Matcher matcher;
matcher = pattern.matcher(word);
boolean checker = matcher.find();
if (checker) { return true; }
return false;
}

我错过了什么?

这里有一些问题:

字符类中的
  • -创建了字符的范围,因此-_无意中包含了空间和_之间的每个ASCII字符,其中包含了大多数";特殊字符";在键盘上(但不是全部(。您需要使用反斜杠对其进行转义(\,因为反斜杠本身也需要在Java中进行转义(
  • Matcher.find()检查是否有任何子字符串匹配,而不是整个字符串。您想要Matcher.matches()
  • 您的条件已反转。如果您希望它返回true(如果特殊字符(,它应该反转您的检查

任何字符串与当前代码匹配都不完全正确——例如{}不匹配——但它肯定比预期的范围更广。

固定代码:

public static boolean checkSpecialChars(String word) {
Pattern pattern = Pattern.compile("[a-zA-Z0-9 \-_]+", Pattern.MULTILINE);
Matcher matcher;
matcher = pattern.matcher(word);
boolean checker = matcher.matches();
return !checker;
}

最新更新