Does Python support conditional structure in regex?
Python是否支持正则表达式中的条件结构?
-
If yes, why I can't have the following (using lookahead in the if part) right? Any way to make Python support it?
如果是的话,为什么我不能拥有以下(在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
-
Using backreference as the if part works, however:
但是,使用反向引用作为if部分可以工作:
>>> 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.
JGsoft引擎,Perl,PCRE,Python和.NET框架支持条件。
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.
我的Python是2.7.3。我不知道如何检查re模块的版本(我该怎么办?)。谢谢。
1 个解决方案
#1
6
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)
.Python支持使用编号或命名捕获组的条件。 Python不支持使用环视的条件,即使Python确实支持外部条件的外观。而不是条件(?(?= regex)then then),你可以交替使用两个相反的外观:(?= regex)然后|(?!regex)else)。
#1
6
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)
.Python支持使用编号或命名捕获组的条件。 Python不支持使用环视的条件,即使Python确实支持外部条件的外观。而不是条件(?(?= regex)then then),你可以交替使用两个相反的外观:(?= regex)然后|(?!regex)else)。