问题
For expression (?<!foo)
,Negative Lookbehind ,asserts that what immediately precedes the current position in the string is not foo.
Now to match string not ending with characters abc
.
The formal expression is \w+(?<!abc)\b
or \b\w+(?<!abc)\b
.
echo "xxabc jkl" | grep -oP '\w+(?<!abc)\b'
jkl
Let's try another form: \w+\b(?<!abc)
.
echo "xxabc jkl" | grep -oP '\w+\b(?<!abc)'
jkl
It get correct answer too.
In my opinion, \w+\b(?<!abc)
is not a Negative Lookbehind,nothing behind (?<!abc)
,it can't called Negative Lookbehind.
1.Is expression \w+\b(?<!abc)
a Negative Lookbehind?
2.Why \w+\b(?<!abc)
has the same effct as \w+(?<!abc)\b
?
回答1:
1)It is a negative lookback window. Negative lookback is used if you want to match something not proceeded by something else.
?<!abc
is a negative look back window. So it will only be true if the proceeding tokens are not "abc" which is true with the string provided: "xxabc jkl"
technically, a space is proceeding "jkl"
Therefore it matches.
2) \b
looks for a word boundary. Word boundaries apply for spaces and end of strings which are present in both of your regular expressions. If you really want to see a difference, try taking the space out of the input. So
use "xxabcjkl"
来源:https://stackoverflow.com/questions/45646773/negative-lookbehind-expression-for-not-ending-with-exp-wexp-b-or-w