繁体   English   中英

如何在python中使用RE组替换字符串?

[英]How to replace string using RE group in python?

在python中使用RE模块时遇到问题:

import re
url='http://list.xxx.com/0-20356-1-0-0-0-0-0-0-0-269036.html'
re_rule=re.compile('.+20356\-(\d{1,3})-0-0-0.+')
new_url=re_rule.sub('2 \1')

如我所愿, new_url将是 ' http://list.xxx.com/0-20356-2-0-0-0-0-0-0-0-269036.html ',但 python 返回new_url=2 .
我知道我在使用 re 模块时犯了错误。 我犯了哪些错误以及如何纠正它们?

鉴于您的示例,为什么还要费心使用re

url = 'http://list.xxx.com/0-20356-1-0-0-0-0-0-0-0-269036.html'
new_url = url.replace('-1-', '-2-')
print(new_url)

产生你正在寻找的东西:

http://list.xxx.com/0-20356-2-0-0-0-0-0-0-0-269036.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM