为什么会失败?
String n = "h107";
if (n.matches("\\D+")) {
System.out.println("non digit in it");
}
我在上面睡了一个晚上,但仍然没有得到它。我现在有一个解决方案:
if (n.matches(".*\\D+.*")) {
但是在我(也许缺乏知识)中,第一个也应该匹配。原因是它必须匹配一个完整的字符串,那么对于开始的行,'^'字符的意义是什么?
那是重复出现的问题.matches()
:它被错误命名。它不进行正则表达式匹配。而且问题在于,甚至其他语言也已成为这种错误命名的牺牲品(python是一个示例)。
问题在于它将尝试匹配您的整个输入。
使用Pattern
中,Matcher
并且.find()
代替(.find()
不实正则表达式匹配,即查找文本匹配输入的任何地方):
private static final Pattern NONDIGIT = Pattern.compile("\\D");
// in code
if (NONDIGIT.matcher(n).find())
// there is a non digit
实际上,您应该使用Pattern
;; String
的.matches()
将重新编译的图案每次。使用,Pattern
它仅编译一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句