80

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?

7
  • Wouldn't any string be a valid regular expression? I could be wrong Commented Oct 28, 2013 at 9:22
  • 2
    @Haidro no, think of missing brackets and illegal use of special characters Commented Oct 28, 2013 at 9:23
  • @RobinKrahl Ah, touché ;) Commented Oct 28, 2013 at 9:24
  • 2
    is there a way i can use try...except and re.compile in python? will the re.compile validate regex? Commented Oct 28, 2013 at 9:24
  • 8
    @alvas Something like re.compile("(" * 1000 + "a" + ")"*1000) will fail with RuntimeError: maximum recursion depth exceeded instead of re.error Commented Oct 28, 2013 at 9:41

2 Answers 2

108

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.

Sign up to request clarification or add additional context in comments.

6 Comments

@alvas, As long as you're using Regular expression supported by Python.
This is OK for regex syntax errors, but mind also TypeError if the pattern is not a str.
And also RecursionError for regexes similar to this comment. It can also be raised for invalid regex, for example '('*1000+'a'+')'*1000+'('.
@TomaszGandor, user202729, Thank you for the comment.
nevertheless, string{data} is valid regexp
|
6

Another fancy way to write the same answer:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.