1

In order to check to see if a string is a valid regular expression python.

Example:

asdasd="([0-9]{1})";APRI="([0-9]{9})";ADD="([0-9]{1})"

How can i check string is contain valid regular expression ?

Thanks,

3 Answers 3

4

Apply the EAFP approach, compile the expression and handle errors.

For example, unbalanced parenthesis:

>>> import re
>>> re.compile(r"(test")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
Sign up to request clarification or add additional context in comments.

Comments

1

EAFP

Compile it and see.

re.compile(asdasd)

Comments

0

Try your regex code in the Online Regex Tester

https://regex101.com/

Your first example: https://regex101.com/r/gN1tG8/1

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.