dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.
MIT License
36.41k stars 3.27k forks source link

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

Open oceanMIH opened 1 year ago

oceanMIH commented 1 year ago

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

andry81 commented 1 year ago

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.

MegaV0lt commented 1 year ago

Try:

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

PS: the echo no never takes place.

Works like this:

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

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
MegaV0lt commented 1 year ago

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
andry81 commented 1 year ago

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.

oceanMIH commented 1 year ago

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

output is empty

andry81 commented 1 year ago

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*.