繁体   English   中英

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

[英]Negative lookahead regex not working

input1="caused/VBN by/IN thyroid disorder"

要求:找到单词"caused" ,然后是斜线,后跟任意数量的大写字母 - 而后面没有空格+ "by/IN

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

input2="caused/VBN thyroid disorder" 

"by/IN"不会导致,因此它应该匹配

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

caused/[AZ]+ - 单词'导致'+ / +一个或多个大写字母
(?![\\\\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());
    }

输出: caused/VB

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

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

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

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

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

将调整字符类[] +匹配(通过回溯),以便前瞻匹配。

你要做的就是停止回溯,使表达式[] +完全匹配。
这可以通过几种不同的方式完成。

  1. 一个积极的前瞻,然后消费
    "caused(?=(/[AZ]+))\\\\1(?!\\\\s+by/IN)"

  2. 独立的子表达式
    "caused(?>/[AZ]+)(?!\\\\s+by/IN)"

  3. 积极的量词
    "caused/[AZ]++(?!\\\\s+by/IN)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM