1

I have this regex, to match version numbers:

^[1-9]\d{0,1}\.(?!0\d)\d{1,3}\.(?!0\d)\d{1,4}$

Regex itself works and matches "1.0.0" when checked on RegexChecker However, when I try to wrap same regex in a bash script, my code goes in "else" condition. I fail to understand why ?

#!/bin/bash
VERSION='1.0.0'
MATCH_PATTERN='^[1-9]\d{0,1}\.(?!0\d)\d{1,3}\.(?!0\d)\d{1,4}$'
if [[ $VERSION =~ $MATCH_PATTERN ]]; then
  :
else
  echo "Version number format is wrong."
  exit 1
fi

I tried running with debugger using set -x but no luck. Any suggestions ?

m00s3
  • 124
  • 7
  • 5
    Your regex is probably a PCRE (Perl Compatible Regular Expressions). From `man bash`: *the string to the right of the operator is considered a POSIX extended regular expression* – Cyrus Apr 01 '23 at 01:33
  • 2
    See ["Bash Regular Expression -- Can't seem to match any of `\s` `\S` `\d` `\D` `\w` `\W` etc"](https://stackoverflow.com/questions/18514135/bash-regular-expression-cant-seem-to-match-any-of-s-s-d-d-w-w-etc) and ["Why does my regular expression work in X but not in Y?"](https://unix.stackexchange.com/questions/119905/why-does-my-regular-expression-work-in-x-but-not-in-y) – Gordon Davisson Apr 01 '23 at 02:54
  • Aside: see [correct-bash-and-shell-script-variable-capitalization](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization) then rename `VERSION` and `MATCH_PATTERN`. – Ed Morton Apr 01 '23 at 12:18

1 Answers1

4

The bash shell regex is POSIX extended regular expression and does not support \d for digits or (?!...) for negative lookaheads

\d can be replaced with either [0-9] or [:digits:]

(?!0\d) can be replaced with an alternation of either 0 or a number not starting with 0 (0|[1-9][0-9]{0,2})

The pattern ^[1-9][0-9]{0,1}\.(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,3})$ should match the noted PCRE expression.

#!/bin/bash
VERSION='1.0.0'
MATCH_PATTERN='^[1-9][0-9]{0,1}\.(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,3})$'
if [[ $VERSION =~ $MATCH_PATTERN ]]; then
  :
else
  echo "Version number format is wrong."
  echo 1
fi
keraion
  • 516
  • 1
  • 4