繁体   English   中英

使用零宽度的断言否定性提前匹配包含字符串“ abc”的字符串

[英]Using zero-width assertions negative lookahead to match a string that does's contains string “abc”

大家好:我正在尝试使用零宽度断言负提前查找来匹配包含字符串“ abc”的字符串,这就是我得到的:

    Pattern pattern = new Perl5Compiler().compile("((?!abc).)+");
    Perl5Matcher matcher = new Perl5Matcher();
    System.out.println(matcher.matches("abc", pattern));
    System.out.println(matcher.matches("abdas dfas", pattern));
    System.out.println(matcher.matches("d abc ", pattern));
    System.out.println(matcher.matches("fafabcdef", pattern));

结果是:

    false
    true
    false
    false

我不明白的是为什么字符串“ abc”不匹配,断言“ abc”后不包含任何字符。 任何人都可以找出它是如何工作的吗? tks〜

环视开始在位置而不是角色上起作用。 因此,使用字符串"abc" ,您的正则表达式的这一部分:( (?!abc). 开始向前看字符串中"a" 之前位置 该位置是"a"之前的空字符串。 这就是为什么它不匹配。

哼,这与Perl5的实际工作方式有所不同。

$ perl -E'
    for ("abc", "abdas dfas", "d abc ", "fafabcdef") {
        say "$_: ", /((?!abc).)+/ ? "true ($&)" : "false";
    }
'
abc: true (bc)
vabdas dfas: true (abdas dfas)
d abc : true (d )
fafabcdef: true (faf)

它必须具有隐式的^和\\ z。

$ perl -E'
    for ("abc", "abdas dfas", "d abc ", "fafabcdef") {
        say "$_: ", /^((?!abc).)+\z/ ? "true ($&)" : "false";
    }
'
abc: false
abdas dfas: true (abdas dfas)
d abc : false
fafabcdef: false

之所以不匹配,是因为某些位置与/ abc /相匹配。

暂无
暂无

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

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