Java RegEx 负面回顾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18015812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java RegEx negative lookbehind
提问by Sorin
I have the following Java code:
我有以下 Java 代码:
Pattern pat = Pattern.compile("(?<!function )\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());
Why does mat.find()
return true? I used negative lookbehind and example
is preceded by function
. Shouldn't it be discarded?
为什么mat.find()
返回true?我使用了负向后视并example
以function
. 不应该丢弃吗?
采纳答案by Boris the Spider
See what it matches:
看看它匹配什么:
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());
}
}
Output:
输出:
function
xample
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
".
所以首先它会找到function
前面没有“ function
”的 。然后它找到xample
前面是function e
“ function
” ,因此不是“ ”。
Presumably you want the pattern to match the wholetext, not just find matches inthe text.
大概您希望模式匹配整个文本,而不仅仅是在文本中查找匹配项。
You can either do this with Matcher.matches()
or you can change the pattern to add start and end anchors:
您可以这样做,Matcher.matches()
也可以更改模式以添加开始和结束锚点:
^(?<!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.
我更喜欢第二种方法,因为它意味着模式本身定义了它的匹配区域,而不是由它的用法定义的区域。然而,这只是一个偏好问题。
回答by Antti Haapala
Your string has the word "function" that matches \w+, and is not preceded by "function ".
您的字符串具有与 \w+ 匹配的单词“function”,并且前面没有“function”。
回答by Ravi Thapliyal
Notice two things here:
这里要注意两点:
You're using
find()
which returns truefor a sub-stringmatch as well.Because of the above, "function" matches as it is not preceded by "function".
The whole string would have never matched because your regex didn't include spaces.
您正在使用
find()
which 也为子字符串匹配返回true。由于上述原因,“function”匹配,因为它前面没有“function”。
整个字符串永远不会匹配,因为您的正则表达式不包含空格。
Use Mathcher#matches()
or ^
and $
anchors with a negative lookahead instead:
使用Mathcher#matches()
or^
和$
带有否定前瞻的锚点:
Pattern pat = Pattern.compile("^(?!function)[\w\s]+$"); // added \s for whitespaces
Matcher mat = pat.matcher("function example");
System.out.println(mat.find()); // false