Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this regex expression not work?

$ echo '!abcae20' | grep -o -P '(?=.*\d)\w{4,}'

This will output nothing.

But the following works:

$ echo '!abcae20' | grep -o -P '.*?(?=.*\d)\w{4,}'

!abcae20

Could anyone give me an explanation?

like image 658
user3015856 Avatar asked Nov 21 '13 03:11

user3015856


1 Answers

This works:

echo '!abcae20' | grep -o -P '.*?(?=.*\d)\w{4,}

Because the .*? matches the !, the (?=.*\d) matches abcae20, and the \w{4,} matches abcae20.

In this one:

echo '!abcae20' | grep -o -P '(?=.*\d)\w{4,}'

The lookahead matches !abcae20, being greedy. However, the \w{4,} can't match the ! so it fails.

Here is the perl regex debug output for the failing one:

Matching REx "(?=.*\d)\w{4,}" against "!abcae20"
   0 <> <!abcae20>           |  1:IFMATCH[0](8)
   0 <> <!abcae20>           |  3:  STAR(5)
                                    REG_ANY can match 8 times out of 2147483647...
   8 <!abcae20> <>           |  5:    DIGIT(6)
                                      failed...
   7 <!abcae2> <0>           |  5:    DIGIT(6)
   8 <!abcae20> <>           |  6:    SUCCEED(0)
                                      subpattern success...
   0 <> <!abcae20>           |  8:CURLY {4,32767}(11)
                                  ALNUM can match 0 times out of 2147483647...
                                  failed...
like image 86
perreal Avatar answered Nov 15 '22 08:11

perreal