'What is the best way to validate a given regex bash?

I'm looking for something equivalent to the following Python snippet in bash:

import re

try:
    re.compile('[')
    is_valid = True
except re.error:
    is_valid = False


Solution 1:[1]

From the bash documentation on [[ and =~:

The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression’s return value is 2.

Which leads to...

#!/usr/bin/env bash

test_re() {
    [[ x =~ $1 ]]
    [[ $? -ne 2 ]]
}

for re in "$@"; do
    if test_re "$re"; then
        printf "%s\n" "$re is valid"
    else
        printf "%s\n" "$re is not valid"
    fi
done

Example:

$ bash demo.sh "[" "[a-z]"
[ is not valid
[a-z] is valid

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shawn