Python是否支持正则表达式中的条件结构?

时间:2014-06-09 15:12:21

标签: python regex

Python是否支持正则表达式中的条件结构?

  1. 如果是,为什么我不能拥有以下内容(在if中使用前瞻 对吧?有什么方法可以让Python支持吗?

    >>> 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. 然后使用反向引用作为if部分:

    >>> p = re.compile(r'(expr)?(?(1)then|else)')
    
  3. http://www.regular-expressions.info/conditional.html

      

    JGsoft引擎支持条件,Perl,PCRE, Python ,   和.NET框架。

    在regex中使用条件的最接近的解决方案是什么?

    我的Python是2.7.3。我不知道如何检查re模块的版本(我怎么办?)。感谢。

1 个答案:

答案 0 :(得分:6)

根据您引用的文档:

  

Python支持使用编号或命名捕获组的条件。 Python不支持使用环视的条件,即使Python确实支持外部条件的外观。 您可以替换两个相反的外观,而不是类似(?(?=regex)then|else)的条件:(?=regex)then|(?!regex)else)