0

In bash, how do I check if a string variable matches a given regular expression? It should be the fastest and most portable (OS X, Linux) method possible.

Basically I want:

if [ $MY_VAR matches '[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}' ]; then
    echo 'matched'
fi
Tom Fenech
  • 69,051
  • 12
  • 96
  • 131
Justin
  • 38,686
  • 72
  • 185
  • 276

1 Answers1

3

It would be,

if [[ $MY_VAR =~ [A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12} ]]; then
    echo 'matched'
fi

In-order to do an exact string match, you need to add anchors.

$MY_VAR =~ ^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$
Avinash Raj
  • 166,785
  • 24
  • 204
  • 249