我为此创建了这个正则表达式:
(?<!\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
关于java - Java中的正则表达式匹配不属于其他单词的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511230/