Correct regex not working in grep

grepregular expression

I have this regex:

(?<=prefix).*$

which returns any character following string "prefix" and it works fine on any online regex engines (e.g. https://regex101.com). The problem is when I use that regex in bash:

grep '(?<=prefix).*$' <<< prefixSTRING

it does not match anything. Why that regex does not work with grep?

Best Answer

You seem to have defined the right regex, but not set the sufficient flags in command-line for grep to understand it. Because by default grep supports BRE and with -E flag it does ERE. What you have (look-aheads) are available only in the PCRE regex flavor which is supported only in GNU grep with its -P flag.

Assuming you need to extract only the matching string after prefix you need to add an extra flag -o to let know grep that print only the matching portion as

grep -oP '(?<=prefix).*$' <<< prefixSTRING

There is also a version of grep that supports PCRE libraries by default - pcregrep in which you can just do

pcregrep -o '(?<=prefix).*$' <<< prefixSTRING

Detailed explanation on various regex flavors are explained in this wonderful Giles' answer and tools that implement each of them

Related Question