How to check if a string is a valid regex in Python?


In Java, I could use the following function to check if a string is a valid regex (source):

boolean isRegex;
try {
  isRegex = true;
} catch (PatternSyntaxException e) {
  isRegex = false;

Is there a Python equivalent of the Pattern.compile() and PatternSyntaxException? If so, what is it?

Asked By: alvas



Similar to Java. Use re.error exception:

import re

    is_valid = True
except re.error:
    is_valid = False

exception re.error

Exception raised when a string passed to one of the functions here is
not a valid regular expression (for example, it might contain
unmatched parentheses) or when some other error occurs during
compilation or matching. It is never an error if a string contains no
match for a pattern.

Answered By: falsetru

Another fancy way to write the same answer:

import re
except re.error:
Answered By: Amit Gupta
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.