61
votes

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

boolean isRegex;
try {
  Pattern.compile(input);
  isRegex = true;
} catch (PatternSyntaxException e) {
  isRegex = false;
}

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

2
Wouldn't any string be a valid regular expression? I could be wrongTerryA
@Haidro no, think of missing brackets and illegal use of special charactersRobin Krahl
@RobinKrahl Ah, touché ;)TerryA
is there a way i can use try...except and re.compile in python? will the re.compile validate regex?alvas
@alvas Something like re.compile("(" * 1000 + "a" + ")"*1000) will fail with RuntimeError: maximum recursion depth exceeded instead of re.errordbr

2 Answers

88
votes

Similar to Java. Use re.error exception:

import re

try:
    re.compile('[')
    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.

2
votes

Another fancy way to write the same answer:

import re
try:
    print(bool(re.compile(input())))
except re.error:
    print('False')