繁体   English   中英

使用python正则表达式排除'。' 在末尾但不在字符串内

[英]Using python regex to exclude '.' at the end but not inside a string

我正在尝试使用python regex发现@mentions例如@user@user.name

到目前为止,我有:

htmlcontent = re.sub(r'((\@)([\w\.-]+))', r"a href='/users/\3'>\1 /a>", htmlcontent)

当此代码发现@mention结尾于. 它不排除它:

例如嗨@user.name. 你好吗?

到目前为止的输出:

<a href='/users/user.name.'>@user.name. /a>

所需的输出:

<a href='/users/user.name'>@user.name /a> <-不带. name

尝试这个:

re.sub(r'((\@)([\w.-]+[\w]+))', r"<a href='/users/\3'>\1</a>", htmlcontent)

这将使重新引擎知道“。” 和'-'可以在中间-但字符串必须以字符结尾。 在您的示例上运行:

In [3]: htmlcontent = 'Hi @user.name. How are you?'
In [4]: re.sub(r'((\@)([\w.-]+[\w]+))', r"<a href='/users/\3'>\1</a>", htmlcontent)
Out[4]: "Hi <a href='/users/user.name'>@user.name</a>. How are you?"

您可以对进行正面评价. 在比赛结束时

([\w\.-]+)(?=\.\s)?

string = "Hi @user.name. How are you?"
print re.sub(r'@([\w\.-]+)(?=\.\s)?', r"a href='/users/\1'>\1 /a>", string)
#Output
#Hi a href='/users/user.name.'>user.name. /a> How are you?

string = "Hi @user.name How are you?"
print re.sub(r'@([\w\.-]+)(?=\.\s)?', r"a href='/users/\1'>\1 /a>", string)
#Output
#Hi a href='/users/user.name'>user.name /a> How are you?

暂无
暂无

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

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