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
  • 72,334
  • 12
  • 107
  • 141
Justin
  • 42,716
  • 77
  • 201
  • 296

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
  • 172,303
  • 28
  • 230
  • 274