4

示例代码:

#!/usr/bin/env python
import re

print re.sub(r'a+(\d)?', r'\1', "aaaa3")
print re.sub(r'a+(\d)?', r'\1', "aaaa") # error!

第二条print语句给了我一个错误:

3
Traceback (most recent call last):
  File "./bbb.py", line 5, in <module>
    print re.sub(r'a+(\d)?', r'\1', "aaaa")
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 291, in filter
    return sre_parse.expand_template(template, match)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py", line 831, in expand_template
    raise error, "unmatched group"
sre_constants.error: unmatched group

如何使用可能的量词处理这个捕获变量0而不会出错?

注意 (\d)?这里可能是另一个复杂的正则表达式,而不仅仅是一个简单的 as \d,这就是为什么我把我的量词?拿出来的原因(..)

4

1 回答 1

2

在 Python 中,您可以这样做以获取可选组的空反向引用:

>>> print re.sub(r'a+(\d?)', r'\1', "aaaa")

>>> print re.sub(r'a+(\d?)', r'\1', "aaaa123")
123

即使用(\d?)而不是(\d)?

与许多其他正则表达式引擎不同,Python 正则表达式引擎在相应的捕获组无法匹配模式时不会填充反向引用。

于 2015-09-08T17:49:48.220 回答