In Java, I could use the following function to check if a string is a valid regex (source):
JavaScript
x
8
1
boolean isRegex;
2
try {
3
Pattern.compile(input);
4
isRegex = true;
5
} catch (PatternSyntaxException e) {
6
isRegex = false;
7
}
8
Is there a Python equivalent of the Pattern.compile()
and PatternSyntaxException
? If so, what is it?
Advertisement
Answer
Similar to Java. Use re.error
exception:
JavaScript
1
8
1
import re
2
3
try:
4
re.compile('[')
5
is_valid = True
6
except re.error:
7
is_valid = False
8
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.