Java RegEx 负面回顾 [英] Java RegEx negative lookbehind
问题描述
我有以下 Java 代码:
I have the following Java code:
Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());
为什么 mat.find()
返回 true?我使用了负向后视,example
前面是 function
.不应该被丢弃吗?
Why does mat.find()
return true? I used negative lookbehind and example
is preceded by function
. Shouldn't it be discarded?
推荐答案
看看它匹配了什么:
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
".
So first it finds function
, which isn't preceded by "function
". Then it finds xample
which is preceded by function e
and therefore not "function
".
大概您希望模式匹配整个文本,而不仅仅是在文本中查找匹配.
Presumably you want the pattern to match the whole text, not just find matches in the text.
您可以使用 Matcher.matches()
执行此操作,也可以更改模式以添加开始和结束锚点:
You can either do this with Matcher.matches()
or you can change the pattern to add start and end anchors:
^(?<!function )\\w+$
我更喜欢第二种方法,因为它意味着模式本身定义了它的匹配区域,而不是由它的用法定义的区域.不过,这只是个人喜好问题.
I prefer the second approach as it means that the pattern itself defines its match region rather then the region being defined by its usage. That's just a matter of preference however.
这篇关于Java RegEx 负面回顾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!