On Sat, Nov 24, 2012 at 10:29:30PM +0000, Lawrence Steeger wrote:
> Alex Chupin (achupin <achupin <at> cisco.com> writes:
> > $ bash --version; s=12345;if [[ "$s" =~ '^[0-9]+$' ]]; then echo it is a
> number; else echo it is NOT a number; fi

> The single quotes are being used in the match.  If you remove them,
> it will work.

The second sentence is correct, but the first is not.  The single quotes
(or any other kind of quoting) override the =~ and cause the right hand
side to be matched as a string, rather than as a regular expression (or
even a glob).

However, the quotes themselves are not being treated as literal
characters.  They are removed before the string comparison occurs.

imadev:~$ x=abc; if [[ $x =~ 'abc' ]]; then echo match; fi
match

As others have already said, the best way to use =~ is to place the
regular expression in a variable, and then use that variable without
quotes on the right hand side of =~.

re='^[st](uff)*$'; if [[ $string =~ $re ]]; then ...

Reply via email to