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

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

在上面的例子中,"caused/VBN"后面跟着" by/IN",所以 'caused' 不应该匹配。

input2="caused/VBN thyroid disorder" 

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

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

caused/[A-Z]+-- 单词 'caused' + / + 一个或多个大写字母
(?![\\s]+by)-- 负前瞻 - 不匹配空格和 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

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

4

2 回答 2

7

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

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

没有它,您可以获得匹配,但不是您所期望的:

“由/IN 甲状腺疾病引起/VBN”;
 ^^^^^^^^^
 这匹配因为“N by”不匹配“[\\s]+by”
于 2011-03-23T22:54:41.323 回答
3

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

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

  1. 积极的展望,随后是消费
    "caused(?=(/[A-Z]+))\\1(?!\\s+by/IN)"

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

  3. 占有量词
    "caused/[A-Z]++(?!\\s+by/IN)"

于 2011-03-24T04:30:07.793 回答