Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex group reference error [duplicate]

Tags:

python

regex

p = r'([\,|\.]\d{1}$)'
re.sub(p, r"\1", v)

works, but I want to add a zero to the capture group, not replace with capture group '10', how can I do this?

re.sub(p, r"\10", v)

fails:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 275, in filter
    return sre_parse.expand_template(template, match)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py", line 802, in expand_template
    raise error, "invalid group reference"
sre_constants.error: invalid group reference
like image 565
RabbitInAHole Avatar asked Mar 22 '23 09:03

RabbitInAHole


1 Answers

Just wrap the group reference in '\g<#>':

import re
pattern = r'([\,|\.]\d{1}$)'
string = 'Some string .1\n'
rep = r'\g<1>0'
re.sub(pattern, rep, string)
> 'Some string .10\n'

Source: http://docs.python.org/2/library/re.html#re.sub

like image 196
qstebom Avatar answered Apr 02 '23 11:04

qstebom