简体   繁体   English

在正则表达式中转义字符?

[英]Escaping a character in regex?

I am wanting to replace a certain character '@' followed by text (eg @patrick). 我想将某个字符“ @”替换为文本(例如,@ patrick)。 I'm looking to escape the '@' and just having the 'patrick' with the use of a regex expression 我希望使用正则表达式来转义“ @”,而仅使用“ patrick”

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. 根据上述问题,这似乎完全可以满足您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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