示例代码:
#!/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
,这就是为什么我把我的量词?
拿出来的原因(..)
。