5

Why does this match

[[ 'hithere' =~ hi* ]]

but this does not

[[ 'hithere' =~ *there ]]
2
  • 1
    Shouldn't it be '=~ . *there'? Commented Sep 30, 2015 at 17:48
  • Yes, thank you! I imagined it was something simple. Commented Sep 30, 2015 at 17:50

2 Answers 2

7

=~ 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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this helps clarify perfectly. I was expecting to use bash pattern matching but instead using the regex operator.
Note that [[ hithere =~ *there ]] has an exit status of 2 (not 1) to indicate that the regular expression was malformed, rather than a simple failure to match.
You have vicariously helped me add database filtering support to my little mysqldump wrapper, mysqlbkup, so thank you! Added support for both BASH pattern matching and POSIX Regex ;)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.