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

PythonRegexStringValidation

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Another fancy way to write the same answer:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalvasView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonAmit GuptaView Answer on Stackoverflow