简体   繁体   中英

Escaping a character in regex?

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

'"&lt;p&gt;Hello World <a href='/users/@Patrick'>@Patrick</a>&lt;/p&gt;"

When really i want it to return

"&lt;p&gt;Hello World <a href='/users/Patrick'>@Patrick</a>&lt;/p&gt;"

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 = "&lt;p&gt;Hello World @Patrick&lt;/p&gt;"
In [4]: new_content = char_finder.sub(r"<a href='/users/\1'>@\1</a>",content)
In [5]: new_content
Out[5]: "&lt;p&gt;Hello World <a href='/users/Patrick'>@Patrick</a>&lt;/p&gt;"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM