简体   繁体   English

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

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

I have a problem when using RE module 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')

As I wish, the new_url would be ' http://list.xxx.com/0-20356-2-0-0-0-0-0-0-0-269036.html ', but python returns new_url=2 .如我所愿, new_url将是 ' http://list.xxx.com/0-20356-2-0-0-0-0-0-0-0-269036.html ',但 python 返回new_url=2 .
I know I had make mistakes when using re module.我知道我在使用 re 模块时犯了错误。 Which mistakes had I make and how to correct them?我犯了哪些错误以及如何纠正它们?

Given your example, why even bother using 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)

produces what you're looking for:产生你正在寻找的东西:

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