I am wanting to replace a certain character '@' followed by text (eg @patrick). I'm looking to escape the '@' and just having the 'patrick' with the use of a regex expression
charFinder = re.compile("(\@\w+)")
content = charFinder.sub(r"<a href='/users/\1'>\1</a>",content)
return content
So far I have this and its returning
'"<p>Hello World <a href='/users/@Patrick'>@Patrick</a></p>"
When really i want it to return
"<p>Hello World <a href='/users/Patrick'>@Patrick</a></p>"
Thank you in advanced!
Move the @ outside of the capturing group and then add it in the one location where you need it in the template.
charFinder = re.compile("\@(\w+)")
content = charFinder.sub(r"<a href='/users/\1'>@\1</a>",content)
This still uses the @
to make the match, but doesn't put it in the group. You then add it later. For example:
In [1]: import re
In [2]: char_finder = re.compile("\@(\w+)")
In [3]: content = "<p>Hello World @Patrick</p>"
In [4]: new_content = char_finder.sub(r"<a href='/users/\1'>@\1</a>",content)
In [5]: new_content
Out[5]: "<p>Hello World <a href='/users/Patrick'>@Patrick</a></p>"
This appears to be doing exactly what you want it to based on the above question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.