Question

I'm trying to take a string that can be anything like "Hello here is a [URL]www.url.com[/URL] and it's great." and be able to extract whatever is between [URL] and [/URL] and then modify the string so it now becomes "Hello here is a < a href='www.url.com'>www.url.com< /a> and it's great."

So I was thinking maybe I could do a string.split() and then get the text between [URL] and [/URL] and then do a string.replace() with the new part but I wanted to know if there was a simpler solution.

Was it helpful?

Solution

Use regular expressions:

import re
print re.sub(r'\[URL\](.*?)\[/URL\]',r'<a href="\1">\1</a>', "Hello here is a [URL]www.url.com[/URL] and it's great.")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top