Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

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

Open
oceanMIH opened this issue Mar 27, 2023 · 8 comments
Open

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

oceanMIH opened this issue Mar 27, 2023 · 8 comments

Comments

@oceanMIH
Copy link

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
Copy link

andry81 commented Mar 27, 2023

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
Copy link

MegaV0lt commented Mar 27, 2023

Try:

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

@MegaV0lt
Copy link

MegaV0lt commented Mar 27, 2023

PS: the echo no never takes place.

Works like this:

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

@andry81
Copy link

andry81 commented Mar 27, 2023

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
Copy link

MegaV0lt commented Mar 27, 2023

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
Copy link

andry81 commented Mar 27, 2023

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
Copy link
Author

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

output is empty

@andry81
Copy link

andry81 commented Mar 28, 2023

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants