Does Python support conditional structure in regex?
If yes, why I can't have the following (using lookahead in the if part) right? Any way to make Python support it?
>>> p = re.compile(r'(?(?=regex)then|else)')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.7/re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: bad character in group name
Using backreference as the if part works, however:
>>> p = re.compile(r'(expr)?(?(1)then|else)')
http://www.regular-expressions.info/conditional.html says
Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework.
What is the closest solution to use conditionals in regex?
My Python is 2.7.3. I don't know how to check the version of re
module (how can I?). Thanks.
According to the documentation you referenced:
Python supports conditionals using a numbered or named capturing group. Python does not support conditionals using lookaround, even though Python does support lookaround outside conditionals. Instead of a conditional like
(?(?=regex)then|else)
, you can alternate two opposite lookarounds:(?=regex)then|(?!regex)else)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With