Reputation: 69581
Why does this match
[[ 'hithere' =~ hi* ]]
but this does not
[[ 'hithere' =~ *there ]]
Upvotes: 4
Views: 5576
Reputation: 95614
=~
is specifically a regular expressions operator. If you want to match zero or more characters, you'll need .*
instead of just *
.
[[ 'hithere' =~ hi.* ]] && echo "Yes"
Yes
[[ 'hithere' =~ .*there ]] && echo "Yes"
Yes
Without anchors, though, the match will succeed even without wildcards.
[[ 'hithere' =~ hi ]]
[[ 'hithere' =~ there ]]
# Add anchors to guarantee you're matching the whole phrase.
[[ 'hithere' =~ ^hi.*$ ]]
[[ 'hithere' =~ ^.*there$ ]]
For pattern matching, you can use =
with an unquoted value. This uses bash pattern matching instead, which is what you were (evidently) expecting.
[[ 'hithere' = hi* ]] && echo "Yes"
Yes
[[ 'hithere' = *there ]] && echo "Yes"
Yes
Upvotes: 6
Reputation: 6404
For basic regular expression
preceding *
is just a character, not considered as special character of regex.
'*' is an ordinary character if it appears at the beginning of the RE
Source: http://man7.org/linux/man-pages/man7/regex.7.html
Answer by Jeff Bowman works because
[[ 'hithere' =~ .*there ]] && echo "Yes"
there is a .
before *
.
Upvotes: 2