Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python support conditional structure in regex?

Tags:

python

regex

Does Python support conditional structure in regex?

  1. 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
    
  2. 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.

like image 498
Tim Avatar asked Jun 09 '14 15:06

Tim


1 Answers

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).

like image 79
falsetru Avatar answered Oct 11 '22 08:10

falsetru