nick
nick

Reputation: 853

How to replace string using RE group in python?

I have a problem when using RE module in python:

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.
I know I had make mistakes when using re module. Which mistakes had I make and how to correct them?

Upvotes: 1

Views: 69

Answers (1)

Eric Dill
Eric Dill

Reputation: 2206

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

Upvotes: 1

Related Questions