Positive/Negative lookahead with grep and perl

2019-04-05 01:27发布

my login.txt file contains following entries

abc def
abc 123
def abc
abc de
tha ewe

when i do the positive lookahead using perl, i'm getting the following result

cat login.txt | perl -ne 'print if /(?)abc\s(?=def)/'
abc def

when i use grep i'm getting the following result

cat login.txt | grep -P '(?<=abc)\s(?=def)'
abc def

negative lookahed results as follows from perl and grep.

 cat login | perl -ne 'print if /(?)abc\s(?!def)/'
abc 123
def abc
abc de

grep result

cat login.txt | grep -P '(?<=abc)\s(?!def)'
abc 123
abc de

perl matched the def abc for the negative lookahead. but it shouldn't matched def abc, as i'm checking abc then def pattern. grep returning the correct result.

is something missing in my perl pattern ?

3条回答
霸刀☆藐视天下
2楼-- · 2019-04-05 01:45

I would try anchoring your regex like so:

/(^abc\s+(?!def).+)/

This would capture:

abc 123
abc de

The (?) at the beginning of your negative lookahead regex is redundant

查看更多
Bombasti
3楼-- · 2019-04-05 01:54

grep does not include the newline in the string it checks against the regex, so abc\s does not match when abc is at the end of the line. chomp in perl or use the -l command line option and you will see similar results.

I'm not sure why you were making other changes between the perl and grep regexes; what was the (?) supposed to accomplish?

查看更多
霸刀☆藐视天下
4楼-- · 2019-04-05 02:08

In your perl -ne 'print if /(?)abc\s(?!def)/' you asking perl to find abc, then space, then string shouldn't be def. This is successfully matches with def abc, because there is no def after abc here and \s matches with newline.

查看更多
登录 后发表回答