dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

oceanMIH opened this issue · 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

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.

Try:

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

PS: the echo no never takes place.

Works like this:

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

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

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

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.

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

output is empty

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