2013-12-09 82 views
2
p = r'([\,|\.]\d{1}$)' 
re.sub(p, r"\1", v) 

的作品,但我想添加一个零到捕获组,而不是取代捕获组'10',我该怎么做?正则表达式组参考错误

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

失败:

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 
+0

正如我在回答说:应用re.sub(P,R “\ g <1> 0”,v) – qstebom

+0

'[\,| \。]'看起来不正确。你的意思是'[。,]'? – georg

回答

1

使用命名捕获组:

p = r'(?P<var>[\,|\.]\d{1})$' 
re.sub(p, r"\g<var>0", v) 

例如

>>> p = r'(?P<var>[\,|\.]\d{1})$' 
>>> v = '235,5' 
>>> re.sub(p, r"\g<var>0", v) 
'235,50' 
0

最简单的方法(这也可能是唯一的方法,我不肯定实际上)是命名捕获组,然后按名称引用回去吧:

>>> re.sub(p, r'\10', '1.2') 
Traceback (most recent call last): 
    ... 
sre_constants.error: invalid group reference 
>>> p = r'(?P<frac>[\,|\.]\d{1}$)' 
>>> re.sub(p, r'\g<frac>0', '1.2') 
'1.20' 

挑选一些名称比“压裂”更好(我把它拉出来......呃,耳朵,是的,让我们一起去“耳朵”:-))。

克里斯