Python re.sub 替换为匹配的内容 [英] Python re.sub replace with matched content

查看:130
本文介绍了Python re.sub 替换为匹配的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了掌握 Python 中的正则表达式,我试图输出一些在 URL 的一部分中突出显示的 HTML.我的输入是

images/:id/size

我的输出应该是

images/:id/size

如果我在 Javascript 中执行此操作

method = 'images/:id/size';method = method.replace(/\:([a-z]+)/, '$1')警报(方法)

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

<预><代码>>>>方法 = '图像/:id/巨大'>>>re.sub('\:([a-z]+)', '$1', method)'图像/<span>$1</span>/huge'

我不知道,如何让 Python 返回正确的结果而不是 $1?re.sub 甚至是执行此操作的正确函数吗?

解决方案

只需使用 \1 而不是 $1:

在[1]中:导入re在 [2] 中:方法 = 'images/:id/huge'在[3]中:re.sub(r'(:[a-z]+)', r'\1', method)Out[3]: '图像/:id/huge'

另请注意原始字符串的使用 (r'...') 用于正则表达式.它不是强制性的,但不需要转义反斜杠,可以说使代码更具可读性.

Trying to get to grips with regular expressions in Python, I'm trying to output some HTML highlighted in part of a URL. My input is

images/:id/size

my output should be

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

If I do this in Javascript

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

I get the desired result, but if I do this in Python

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

I don't, how do I get Python to return the correct result rather than $1? Is re.sub even the right function to do this?

解决方案

Simply use \1 instead of $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'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

这篇关于Python re.sub 替换为匹配的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆