Python re.sub替换匹配的内容

时间:2011-08-25 13:28:42

标签: python regex

试图掌握Python中的正则表达式,我试图输出部分URL中突出显示的HTML。我的意见是

images/:id/size

我的输出应该是

images/<span>:id</span>/size

如果我在Javascript中执行此操作

method = 'images/:id/size';
method = method.replace(/\:([a-z]+)/, '<span>$1</span>')
alert(method)

我得到了想要的结果,但如果我在Python中这样做

>>> method = 'images/:id/huge'
>>> re.sub('\:([a-z]+)', '<span>$1</span>', method)
'images/<span>$1</span>/huge'

我没有,我如何让Python返回正确的结果而不是$1re.sub甚至是正确的功能吗?

4 个答案:

答案 0 :(得分:75)

只需使用\1代替$1

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

另请注意,raw stringsr'...')用于正则表达式。它不是强制性的,但是不需要转义反斜杠,可以说使代码更具可读性。

答案 1 :(得分:13)

使用\1代替$1

  

\ number匹配相同编号的组的内容。

http://docs.python.org/library/re.html#regular-expression-syntax

答案 2 :(得分:4)

对于替换部分,Python以sed和vi的方式使用\1,使用Perl,Java和Javascript(以及其他)的方式 $1。此外,因为\1在常规字符串中插入为字符U + 0001,所以您需要使用原始字符串或\ escape it。

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

答案 3 :(得分:3)

对整个匹配值的后向引用是\g<0>,请参见re.sub documentation

  

后向引用\g<0>替换RE匹配的整个子字符串。

请参见Python demo

import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
相关问题