我有以下 Java 代码:
Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());
为什么 mat.find()
返回 true?我使用了负向后视,example
前面是 function
。它不应该被丢弃吗?
最佳答案
查看匹配的内容:
public static void main(String[] args) throws Exception {
Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
while (mat.find()) {
System.out.println(mat.group());
}
}
输出:
function
xample
所以它首先找到 function
,它前面没有“function
”。然后它找到 xample
,它前面是 function e
,因此不是“function
”。
大概您希望模式匹配整个文本,而不仅仅是在文本中找到匹配项。
您可以使用 Matcher.matches()
执行此操作,也可以更改模式以添加开始和结束 anchor :
^(?<!function )\\w+$
我更喜欢第二种方法,因为它意味着模式本身定义了它的匹配区域,而不是它的用法定义的区域。然而,这只是一个偏好问题。
关于Java RegEx 负向后视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015812/