否定的前瞻性正则表达式无效

dsa*_*ish 2 java regex regex-negation regex-lookarounds

input1="caused/VBN by/IN thyroid disorder"
Run Code Online (Sandbox Code Playgroud)

要求:找到"caused"后跟斜线后跟任意数量的大写字母的单词- 后面跟不上空格+ "by/IN.

在上面的示例中,"caused/VBN"后面跟着" by/IN",因此'cause'不匹配.

input2="caused/VBN thyroid disorder" 
Run Code Online (Sandbox Code Playgroud)

"by/IN" 不遵循造成的,所以它应该匹配

regex="caused/[A-Z]+(?![\\s]+by/IN)"
Run Code Online (Sandbox Code Playgroud)

caused/[A-Z]+- 单词'引起'+/+一个或多个大写字母
(?![\\s]+by)- 负向前瞻 - 不匹配空格和

以下是我用来测试的简单方法

public static void main(String[] args){
    String input = "caused/VBN by/IN thyroid disorder";

    String regex = "caused/[A-Z]+(?![\\s]+by/IN)";

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);

    while(matcher.find()){
        System.out.println(matcher.group());
    }
Run Code Online (Sandbox Code Playgroud)

输出: caused/VB

我不明白为什么我的负面前瞻正则表达式不起作用.

Mar*_*ers 7

您需要在正则表达式中包含单词边界:

String regex = "caused/[A-Z]+\\b(?![\\s]+by/IN)";
Run Code Online (Sandbox Code Playgroud)

没有它你可以得到一个匹配,但不是你所期望的:

"caused/VBN by/IN thyroid disorder";
 ^^^^^^^^^
 this matches because "N by" doesn't match "[\\s]+by"