我已经为此创建了这个正则表达式:
(?<!w)name(?!w)
我预计这将与以下内容相匹配:
name
(name)
但不应匹配以下内容:
myname
names
我的问题是,如果我在Java中使用这种模式,它不适用于使用不同于空格的其他符号(如括号)的情况。
我在这个网站上测试了正则表达式(http://gskinner.com/RegExr/,这是一个非常好的网站(顺便说一句),它很有效,所以我想知道Java是否需要不同的语法。
String regex = "((?<!\w)name(?!\w))";
"(name".matches(regex); //it returns false
为什么不使用单词边界?
Pattern pattern = Pattern.compile("\bname\b");
String test = "name (name) mynames";
Matcher matcher = pattern.matcher(test);
while (matcher.find()) {
System.out.println(matcher.group() + " found between indexes: " + matcher.start() + " and " + matcher.end());
}
输出:
name found between indexes: 0 and 4
name found between indexes: 6 and 10
使用"单词边界"正则表达式b
:
if (str.matches(".*\bname\b.*")
// str contains "name" as a separate word
请注意,这将与"foo_name bar"或"foo name1 bar"不匹配,因为下划线和数字被视为单词字符。如果你想在"name"周围匹配一个"非字母",使用这个:
if (str.matches(".*(^|[^a-zA-Z])name([^a-zA-Z]|$).*")
// str contains "name" as a separate word
请参阅Regex字边界