1

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Because my given code is only an example,actually I'm writing a function ,there are lots of urls to reset,so I tried re . Your answer has solved my problems,and then ,can you tell me how to achieve using re?
You could essentially do the same thing with re.sub. re.sub('-1-', '-2-', url) will produce the same thing as the url.replace code above. There are some extra flags on re.sub that make it more versatile. Have a look at the docs here: docs.python.org/2/library/re.html#re.sub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.