1

I am using the module re in Python 3.3 to work with regular expressions. Users give my program a string (supposed to be regex) and it has to work with that regex.

I think it is pretty impossible, but, is there any way to know if a string is a valid regex?

Thank you!

1
  • Not sure what you want to use this for, but be aware that certain regular expressions can cause a denial of service; it's not wise to let users enter regular expressions which you're going to use Commented Apr 1, 2014 at 16:14

3 Answers 3

4

You can simply try to compile the regex using re.compile(), and an re.error will be thrown if the regex is invalid.

try:
    re.compile(regex)
except re.error:
    # not valid
Sign up to request clarification or add additional context in comments.

Comments

1

I think that trying to re.compile() and catch errors is the most useful way, but depending on how complicated the regex can be, it could also be possible to use a regex to test if a given string is a regex...

(But I think to describe all valid Python regexes, you need at least a context free grammar)

Comments

0

You can try compiling it within a try finally. This won't catch use case when a user accidentally makes a valid regex, but it will catch any instance when he supplies an invalid one. You can try replacing the invalid '++' string with something valid like '[1-9]' to see it work.

import re

try:
    r = re.compile('++')
except:
    print 'Invalid Regex'
else:
print 'Regex valid'

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.