Code example:
import re
print re.sub(r'a+(\d)?', r'\1', "aaaa3")
print re.sub(r'a+(\d)?', r'\1', "aaaa")
The second statement printgives me an error:
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
How can I handle this capture variable with a probable quantifier 0without error?
Note (\d)? here may be another complex regex, not just how \d, so I output my quantifier ?out (..).
source
share