python re.sub group: \number 之后的数字
如何用 foo123bar
替换 foobar
?
这不起作用:
>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'
这起作用:
>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'
How can I replace foobar
with foo123bar
?
This doesn't work:
>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'
This works:
>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案是:
文档的相关摘录:
The answer is:
Relevant excerpt from the docs:
对于这个问题,我更愿意通过使用以下内容来匹配而不是捕获。
将
'foo'
之后的零宽度字符串(考虑'foo'
和'bar'
)替换为'123'
。(?<=foo)
是一个正向回顾。Demo
当然也有需要捕获组的情况,比如
Here
不起作用,因为Python 的默认正则表达式引擎不支持可变长度后向查找(但是替代的 PyPI 正则表达式模块 支持) 。
For this problem I would prefer to match but not capture, by employing the following.
which replaces the zero-width string after
'foo'
(think between'foo'
and'bar'
) with'123'
.(?<=foo)
is a positive lookbehind.Demo
There are of course situations where a capture group is needed, such as
Here
does not work because Python's default regex engine does not support variable-length lookbehinds (the alternative PyPI regex module does, however).