这是我的代码,用于确定单词是否包含任何非字母数字字符:
String term = "Hello-World";
boolean found = false;
Pattern p = Pattern.Compile("\\W*");
Matcher m = p.Matcher(term);
if(matcher.find())
found = true;
我想知道正则表达式是否错误。我知道"\W"
会匹配任何非单词字符。你知道我错过了什么吗??
发布于 2011-04-01 04:53:23
将正则表达式更改为:
.*\\W+.*
发布于 2016-03-02 19:00:34
现在是2016年或更晚,你应该考虑其他字母表中的国际字符串,而不仅仅是拉丁语。在这种情况下,经常引用的[^a-zA-Z]
将不匹配。现在在Java中有更好的方法:
[^\\p{IsAlphabetic}^\\p{IsDigit}]
请参阅the reference (“Unicode脚本、块、类别和二进制属性的类”一节)。还有一个我觉得很有用的this answer。
发布于 2011-04-01 05:01:47
方法的大小写错误。
匹配器被声明为m,但用作匹配器。
重复应该是“一个或多个”+,而不是“零或多个”*这是正确的:
String term = "Hello-World";
boolean found = false;
Pattern p = Pattern.compile("\\W+");//<-- compile( not Compile(
Matcher m = p.matcher(term); //<-- matcher( not Matcher
if(m.find()) { //<-- m not matcher
found = true;
}
顺便说一句,如果你只需要:
boolean found = m.find();
:)
https://stackoverflow.com/questions/5506154
复制相似问题