实际上,我想检查它是否只有字母数字加上这些:.-_ [空格]
如果使用外部库,我想使用 Guava,因为它已经包含在我的项目中...
最佳答案
无正则表达式且更具可读性(?)的解决方案可以使用 Guava 的 CharMatcher
类:
boolean matched = CharMatcher.JAVA_LETTER_OR_DIGIT.or(CharMatcher.WHITESPACE)
.or(CharMatcher.anyOf("_.-")).matchesAllOf(yourString);
也许 ASCII 字符适合您的用例?如果是这样,请使用:
boolean matched = CharMatcher.ASCII.matchesAllOf(yourString);
参见 wiki page示例和描述。
此外,您可能希望将匹配器提取为常量并预先计算它:
private static final CharMatcher CHAR_MATCHER = CharMatcher.JAVA_LETTER_OR_DIGIT
.or(CharMatcher.WHITESPACE)
.or(CharMatcher.anyOf("_.-"))
.precomputed();
更有趣的是,如果您阅读 CharMatcher
的文档,您可能会发现 "digit" , "letter"和 "whitespace"在 Java 中是非常模糊的术语:
Determines whether a character is a digit according to Java's definition. If you only care to match ASCII digits, you can use
inRange('0', '9')
.
或
Determines whether a character is a letter according to Java's definition. If you only care to match letters of the Latin alphabet, you can use
inRange('a', 'z').or(inRange('A', 'Z'))
.
因此您可能希望使用明确的字符范围:
private static final CharMatcher CHAR_MATCHER_ASCII =
CharMatcher.inRange('0', '9')
.or(CharMatcher.inRange('a', 'z'))
.or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.anyOf(" _.-")) // note space here
.precomputed();
关于java - 如何检查字符串在 Guava 中是否只有字母数字字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510255/