Get an error while trying to use the `\ 1` that come from regex` (\ d)? `In Python

Code example:

#!/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!

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 (..).

+4
source share
1 answer

In Python, you can do this to get an empty backlink for an optional group:

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

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

i.e. use (\d?)instead(\d)?

Pajon regex engine, , , .

+2

Source: https://habr.com/ru/post/1606464/


All Articles