1

I'm under bash and tried to match a short string with a pattern:

$[[ "ab" =~ "^a*" ]]
$echo $?
0

OK, as I expected, but then I changed into "^b*", I expect this time, it doesn't match:

$[[ "ab" =~ "^b*" ]]
$echo $?
0

Strangely the return value is still "OK". Why is that, where did I get wrong? Thanks.

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119

2 Answers2

2

Regex ^b* means 0 or more b at the start so obviously it will return true for any input.

You should use + quantifier for 1 or more matches and avoid quoting regex in bash as this:

[[ "ab" =~ ^a+ ]] && echo 'ok' || echo 'no'
ok

[[ "ab" =~ ^b+ ]] && echo 'ok' || echo 'no'
no

Likewise you can use ^a or ^a.* as well.

F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

In addition to anubhava's correct answer, and because bash's regex are particulary expensive, I would say:

If your need is to check for presence of a character at 1st position of a string, and because this kind of test have to be done against variables:

myVar="ab"

[ "$myVar" ] && [ -z "${myVar%%a*}" ] && echo "String '$myVar' begin with 'a'"

will output: String 'ab' begin with 'a', but

myVar="ab"

[ "$myVar" ] && [ -z "${myVar%%b*}" ] && echo "String '$myVar' begin with 'b'"

won't produce anything!

See also: String contains in Bash

F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137