You can do it like this:
import re
text = "hello this [is a cool] line of text that might have [two] brackets."
brackets = re.compile(r'\[(.*?)\]')
new_text = brackets.sub(lambda x: f'<a href=/phrases/{x.group(1)}>{x.group(1)}</a>', text)
print(new_text)
This will replace the pattern with what the lambda returns:
x.group(1)
returns the first group in the regex pattern (indexing starts from 1): (.*?)
, meaning it will return only the text in between brackets and then format it using f strings
.
To also remove any punctuation from the text in the brackets this code could be used (notice how the end result doesn't have any of the .
that were in between the brackets):
import re
import string
text = "hello this [is a..... cool] line of text that might have [two] brackets."
def replace_with_link(match):
info = match.group(1)
info = info.translate(str.maketrans('', '', string.punctuation))
return f'<a href="/phrases/{info}">{info}</a>'
brackets = re.compile(r'\[(.*?)\]')
new_text = brackets.sub(replace_with_link, text)
print(new_text)