2

In bash I have the following:

REGEX="(1.0.0|2.0.0)"
declare -a arr=("A:1.0.0" "B:1.0.0" "C:2.0.0" "D:2.0.1")
for i in "${arr[@]}"
do
    echo "Found: $i"
    if [[ "$i"=~"${REGEX}" ]]; then
        echo "$i matches: ${REGEX}"
    else
        echo "$i DOES NOT match: ${REGEX}"
    fi   
done

I would assume that for D:2.0.1 it would print ...DOES NOT match... but instead it prints

Found: A:1.0.0
A:1.0.0 matches: (1.0.0|2.0.0)
Found: B:1.0.0
B:1.0.0 matches: (1.0.0|2.0.0)
Found: C:2.0.0
C:2.0.0 matches: (1.0.0|2.0.0)
Found: D:2.0.1
D:2.0.1 matches: (1.0.0|2.0.0)

So what is wrong with my REGEX group pattern? Specifying a group pattern like that works fine in other languages - e.g. like groovy.

u123
  • 15,603
  • 58
  • 186
  • 303

1 Answers1

6

You have a a typo in the regex match expression to start with

if [[ "$i"=~"${REGEX}" ]]; then

should have been written as just

if [[ $i =~ ${REGEX} ]]; then

which implicates the point that you should never quote your regex expressions. For it to understand the | operator in its extended regular expressions support(ERE) you need to make it understand that it is not a literal string which it treats so when under double-quotes.


Not recommended

But if you still want to quote your regex strings - bash 3.2 introduced a compatibility option compat31 (under New Features in Bash 1.l) which reverts bash regular expression quoting behavior back to 3.1 which supported quoting of the regex string. You just need to enable it via an extended shell option

shopt -s compat31

and run it with quotes now

if [[ $i =~ "${REGEX}" ]]; then
Inian
  • 80,270
  • 14
  • 142
  • 161