Reputation: 5890
if [[ 23ab = *ab ]] ; then echo yes; fi
Is the above code a regular expression?
Please see the following:
if [[ 23ab =~ [0-9]{1,2}ab ]] ; then echo yes; fi
So which line is a regex? If the first line is not a regex, why does it work when we are using *?
If it is, but when we instead of =~
just using =
, like
if [[ 23ab = [0-9]{1,2}ab ]]
, it doesn't work right now.
Can you explain the difference between the two lines?
Upvotes: 3
Views: 444
Reputation: 295619
[[ $a =~ $b ]]
is a regular expression match. In this syntax, *
matches 0-n instances of the immediately preceding character or pattern.
[[ $a = $b ]]
is a glob-style pattern match. In this syntax, *
matches 0-n characters of any type.
Note that it is important that regular expressions in bash be stored in variables. That is:
re='[0-9]{1,2}ab'
[[ $foo =~ $re ]]
may actually be different from
[[ $foo =~ [0-9]{1,2}ab ]]
...depending on which version of bash you're running. Always using a variable will prevent this from causing problems.
Note that these are both different from
re='[0-9]{1,2}ab'
[[ $foo =~ "$re" ]] ## <- LITERAL SUBSTRING MATCH _NOT_ REGULAR EXPRESSION MATCH
...in which case the quoting makes the contents of $re
literal, ie. not treated like a regular expression in modern bash.
Upvotes: 5