Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy regex operator doesn't work in bash

Tags:

regex

bash

expr

echo "$(expr "title: Purple Haze       artist: Jimi Hendrix" : 'title:\s*\(.*\?\)\s*artist.*' )"

prints

Purple Haze             

With the trailing whitespace, even though I am using the ? lazy operator.

I've tested this on https://regex101.com/ and it works as expected, what's different about bash?

like image 846
texasflood Avatar asked Nov 16 '25 09:11

texasflood


1 Answers

You aren't using bash's regexp matching, you're using expr. expr does not have a “? lazy operator”, it only implements basic regular expressions (with a few extensions in the Linux version, such as \s for whitespace, but that doesn't include Perl-like lazy operators). (Neither does bash, for that matter.)

If you don't want .* to include trailing space, specify that it must end with a character that isn't a space:

'title:\s*\(.*\S\)\s*artist.*'
like image 89
Gilles 'SO- stop being evil' Avatar answered Nov 18 '25 12:11

Gilles 'SO- stop being evil'