开发者

Using zero-width assertions negative lookahead to match a string that does's contains string "abc"

开发者 https://www.devze.com 2023-02-19 10:49 出处:网络
Hi all: I\'m trying using zero-开发者_C百科width assertions negative lookahead to match a string that does\'s contains string \"abc\",and this is what I got:

Hi all: I'm trying using zero-开发者_C百科width assertions negative lookahead to match a string that does's contains string "abc",and this is what I got:

    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));

and the result is:

    false
    true
    false
    false

What I can't understand is why the string "abc" doesn't matches, it doesn't contains any character after the assertion "abc". Can anyone please figure out how this works? tks~


Look-arounds start doing their thing on positions, not on characters. So, with the string "abc", this part of your regex: (?!abc). starts looking ahead on the position before the "a" in your string. The position is the empty string before "a". That's why it fails to match.


Hum, that differs from how Perl5 actually works.

$ 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)

It must have an implicit ^ and \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

The ones that don't match because there some position that matches /abc/.

0

精彩评论

暂无评论...
验证码 换一张
取 消