I have this text:
Lorem ipsum [!one] and [!two]
And I need to get to this text:
Lorem ipsum [one](http://example.com/one) and [two](http://example.com/two)
This code finds each word between "[!" and "]"
import re
r = r"\[\!(\w+)\]"
text = "Lorem ipsum [!one] and [!two]"
result = re.findall(r, text)
This gives me the following result
['one', 'two']
I could use .replace() but I was wondering if this is doable with regex.
Edit:
I needed the matched text to be processed a bit before replacing it. This is the solution using the answer as a starting point:
import re
def generate_url(input):
# Do extra stuff here
return "http://example.com/%s" % input
input = '''Lorem ipsum [!one] and [!two]'''
regex = "\[@([^]]+)\]"
url_generator = lambda match: "[%s](%s)" % (match.group(1), generate_url(match.group(1)))
output= re.sub(regex, url_generator, input)