-2

This regular expression check in shell script always false despite it matches with $LIST values.

#!/usr/bin/env bash

LIST="AB,CD,EF" # Valid value and should print "VALID!"

if [[ ! "$LIST" =~ ^[A-Z]{2}(?:,[A-Z]{2})*$ ]]
then
    echo "INVALID"
else
    echo 'VALID!'
fi

For the regex, some of the invalid $LIST values would be AB,CD,EF,, AB,CD,ef.

What could be the reason for this?

Sachith Dickwella
  • 1,388
  • 2
  • 14
  • 22

1 Answers1

1

Your regex:

^[A-Z]{2}(?:,[A-Z]{2})*$

Is not POSIX regex compliant because (?:...) (non-capturing group) is not supported in BASH regex which is a POSIX extended regular expression.

Use a capturing group instead:

^[A-Z]{2}(,[A-Z]{2})*$
anubhava
  • 761,203
  • 64
  • 569
  • 643