Why is this negative lookbehind considered a successful regular expression?

I would expect this simple text string to not be considered a match:

xyz@xyz:~$ echo xy | perl -n -e 'print if /y(?<!x)/'
xy

But, oddly enough, it is. I tried this also @ https://regex101.com/ and the result is the same. It seems like it will match y, which bothers me. If my understanding is correct, the above regular expression should match only ythat is not preceded x.

PS: I gave this a simplified example. In general, I would like to use negative lookbehinds to match whole strings and not necessarily single characters like x.

I use Perl regex flavor.

thank

+4
source share
2 answers

You have a negative approval position back.

This is zero width, so it yshould be before you wrote it.

Given:

$ echo $'xy\nay\nyx' 
xy
ay
yx

The lookbehind image /y(?<!x)/matches the lines with xfront or back ybecause it yis behind this statement (not x):

$ echo $'xy\nay\nyx' | perl -n -e 'print if /y(?<!x)/'
xy
ay
yx

Note that it yxalso matches the statement preceding xand looks at y, so all three lines match.

What are you looking for:

$ echo $'xy\nay\nyx' | perl -n -e 'print if /(?<!x)y/'
ay
yx

Demo

Further explanation.

Or you need to consider the width y(or whatever it matches) if you look in the opposite direction after y, including in the statement y:

$ echo $'xy\nay\nyx' | perl -n -e 'print if /y(?<!xy)/'
ay
yx
+5
source

ab a, b. , y , , x. x — y — .

/(?<!x)y/

/(?:^|[^x])y/
+5

Source: https://habr.com/ru/post/1676701/


All Articles