试图掌握Python中的正则表达式,我试图输出一些在URL的一部分中突出显示的HTML.我的意见是
images/:id/size
Run Code Online (Sandbox Code Playgroud)
我的输出应该是
images/<span>:id</span>/size
Run Code Online (Sandbox Code Playgroud)
如果我在Javascript中这样做
method = 'images/:id/size';
method = method.replace(/\:([a-z]+)/, '<span>$1</span>')
alert(method)
Run Code Online (Sandbox Code Playgroud)
我得到了理想的结果,但是如果我用Python做的话
>>> method = 'images/:id/huge'
>>> re.sub('\:([a-z]+)', '<span>$1</span>', method)
'images/<span>$1</span>/huge'
Run Code Online (Sandbox Code Playgroud)
我没有,我如何让Python返回正确的结果而不是$1?是re.sub连做这个正确的功能?
NPE*_*NPE 82
只需使用\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'
Run Code Online (Sandbox Code Playgroud)
还要注意对正则表达式使用原始字符串(r'...').它不是强制性的,但不需要转义反斜杠,可以说使代码更具可读性.
小智 15
用\1而不是$1.
\number匹配相同编号的组的内容.
http://docs.python.org/library/re.html#regular-expression-syntax
对于替换部分,Python使用\1sed和vi 的方式,而不是 $1 Perl,Java和Javascript(以及其他方式)的方式。此外,由于将\1常规字符串插入为字符U + 0001,因此您需要使用原始字符串或将其转义。
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'
>>>
Run Code Online (Sandbox Code Playgroud)
整个匹配值的后向引用是\g<0>,请参阅re.sub文档:
反向引用将
\g<0>替换RE匹配的整个子字符串。
参见Python演示:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
Run Code Online (Sandbox Code Playgroud)