pure-bash-bible icon indicating copy to clipboard operation
pure-bash-bible copied to clipboard

[[ ' aaaa' =~ a* ]] && echo ${BASH_REMATCH[0]} || echo no

Open oceanMIH opened this issue 3 years ago • 8 comments

the output is empty, I think it be aaaa ? would you please tell me why this happened? I made some effort to resolve ths, but failed... image

oceanMIH avatar Mar 27 '23 11:03 oceanMIH

the output is empty, I think it be aaaa ?

I think it does match the empty sequence at first.

I made some effort to resolve ths, but failed...

[[ ' aaaa' =~ aa* ]] && echo ${BASH_REMATCH[0]} || echo no
[[ ' aaaa' =~ a+ ]] && echo ${BASH_REMATCH[0]} || echo no

The last example in your picture is not reproducible.

andry81 avatar Mar 27 '23 16:03 andry81

Try:

re='(a+)'
[[ ' aaaa' =~ $re ]] && echo ${BASH_REMATCH[0]} || echo no
aaaa

MegaV0lt avatar Mar 27 '23 16:03 MegaV0lt

PS: the echo no never takes place.

Works like this:

re='(a+)'
[[ ' bbbb          ' =~ $re ]] && { echo ${BASH_REMATCH[0]} ;} || echo no
no

MegaV0lt avatar Mar 27 '23 16:03 MegaV0lt

Try:

re='(a+)'
[[ ' aaaa' =~ $re ]] && echo ${BASH_REMATCH[0]} || echo no
aaaa

It has no difference with this:

[[ ' aaaa' =~ (a+) ]] && echo ${BASH_REMATCH[0]} || echo no
aaaa

andry81 avatar Mar 27 '23 16:03 andry81

but you must use the extra curly braces to get the no when the regex is not found

[[ ' aaaa          ' =~ (a+) ]] && { echo ${BASH_REMATCH[0]} ;} || echo no
aaaa
[[ ' bbbb          ' =~ (a+) ]] && { echo ${BASH_REMATCH[0]} ;} || echo no
no

MegaV0lt avatar Mar 27 '23 17:03 MegaV0lt

but you must use the extra curly braces to get the no when the regex is not found

[[ ' aaaa          ' =~ (a+) ]] && { echo ${BASH_REMATCH[0]} ;} || echo no
aaaa
[[ ' bbbb          ' =~ (a+) ]] && { echo ${BASH_REMATCH[0]} ;} || echo no
no

Second expression does not match irrespective to the braces.

andry81 avatar Mar 27 '23 17:03 andry81

excuse me, let me make point clear, why the following output is empty? [[ ' aaaa' =~ a* ]] && echo ${BASH_REMATCH[0]}

output is empty

oceanMIH avatar Mar 28 '23 01:03 oceanMIH

excuse me, let me make point clear, why the following output is empty? [[ ' aaaa' =~ a* ]] && echo ${BASH_REMATCH[0]}

output is empty

Output is empty because a* has matched an empty string.

This is legit match or not greedy match. Lazy match example:

[[ ' aaaa          ' =~ .*a* ]] && { echo ${BASH_REMATCH[0]} ;} || echo no
aaaa

In greedy regex expressions mode the .* does consume everything before the a*.

andry81 avatar Mar 28 '23 01:03 andry81