quickshiftin
quickshiftin

Reputation: 69581

Bash regex =~ operator match prefix

Why does this match

[[ 'hithere' =~ hi* ]]

but this does not

[[ 'hithere' =~ *there ]]

Upvotes: 4

Views: 5576

Answers (2)

Jeff Bowman
Jeff Bowman

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

rajuGT
rajuGT

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

Related Questions