Vix Lee
Vix Lee

Reputation: 91

python - check string contain a valid regular expression python

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,

Upvotes: 1

Views: 962

Answers (3)

ode2k
ode2k

Reputation: 2723

Try your regex code in the Online Regex Tester

https://regex101.com/

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

Upvotes: 0

alecxe
alecxe

Reputation: 473873

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

Upvotes: 4

Brian Cain
Brian Cain

Reputation: 14619

EAFP

Compile it and see.

re.compile(asdasd)

Upvotes: 1

Related Questions