regexbash

Linux character class matching not working for this expression


I'm trying to write a matcher that matches any of v1.65.x, v1.66.x or v1.67.x. But the moment I introduce a character class, it doesn't work with either a list of characters or a range:

if [[ "v1.67.x" =~ "v1.67" ]]; then echo matches; else echo no match fi

outputs

matches

With Character class

if [[ "v1.67.x" =~ "v1.6[7]" ]]; then echo matches; else echo no match; fi

outputs

 no match

What am I doing wrong?


Solution

  • This is explained in the fine manual:

    If any part of the pattern is quoted, the quoted portion is matched literally. This means every character in the quoted portion matches itself, instead of having any special pattern matching meaning.

    Without quotes it works:

    if [[ "v1.67.x" =~ v1.6[7] ]]; then echo matches; else echo no match; fi
    

    EDIT: as mentioned in the comments (now deleted), to prevent incorrect matches, use quotes around the literal part of the match:

    if [[ "v1.67.x" =~ "v1.6"[7] ]]; then echo matches; else echo no match; fi
    

    Otherwise the . will match any character.