【发布时间】:2021-03-25 19:46:36
【问题描述】:
不管我通过这个函数,一切都是真的。
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;
}
我错过了什么?
【问题讨论】:
-
试试
Pattern.compile("^[a-zA-Z0-9 -_]+", Pattern.MULTILINE);。 -
您的问题根本不清楚,例如
asd没有特殊字符;那它为什么要返回false?你的意思是,它应该为a, s, d, 1, 2, 3, -, and _以外的任何字符返回true? -
另外:
find()查找子序列。如果要匹配整个输入,请使用matches()。 -
@ArvindKumarAvinash 这些都是例子。我只想包括'a-zA-Z0-9 -_',无论我尝试什么,它都是真的。表示有特殊字符。
-
@letsCode - 在这种情况下,您应该用一条语句替换整个函数体,
return !Pattern.compile("[a-zA-Z0-9_-]+", Pattern.MULTILINE).matcher(word).matches();