4

I am trying to use the extended regex operators available in bash (?, *, +, @, !). The manual says I just have to enclose with parentheses a list of patterns, then use the operator before the left bracket. So if I want a pattern of zero or more a's:

if [[ "$1" =~ *(a) ]]
then
   echo $1
fi

but this is not working. What am I doing wrong?

KevinRGT
  • 389
  • 2
  • 5
  • 14
  • Where exactly in the docs does it say the operator must go before the group? That's not the case in any regex engine I know, and it's not for bash either. (Even if it was, "zero or more a's" matches any string.) – Mat Sep 27 '12 at 04:54
  • This looks like a dupe of [How do I use regular expressions in bash scripts?](http://stackoverflow.com/questions/304864/how-do-i-use-regular-expressions-in-bash-scripts) – James Sep 27 '12 at 04:55
  • Here: http://www.gnu.org/software/bash/manual/bashref.html#Pattern-Matching – KevinRGT Sep 27 '12 at 05:07

1 Answers1

10

Per man bash:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

I quoted the whole thing here because I think it's useful to know. You use standard POSIX extended regular expressions on the right hand side.

In particular, the expression on the right side may match a substring of the left operand. Thus, to match the whole string, use ^ and $ anchors:

if [[ "$1" =~ ^a*$ ]]
then
    echo $1
fi
Michael
  • 8,362
  • 6
  • 61
  • 88
nneonneo
  • 171,345
  • 36
  • 312
  • 383