首页 > 解决方案 > 推特用户名的正则表达式,但某些匹配指定格式 - Python

问题描述

我是正则表达式的新手。我目前正在尝试用@MENTION 替换推文中的所有用户名,除了我之前已经更改为@CEO、@COMPANY 和@MEDIA 的用户名。

最终的解决方案应该是这样的:最初的推文:“@John 被@COMPANY 告知他不会收到他的奖金,@MEDIA 报道。” 最后一条推文:“@MEDIA 报道,@COMPANY 告诉@MENTION 他不会收到奖金。”

我尝试了不同的版本,但无法解决它们。如果您能提供帮助,将不胜感激。

这是一次尝试,我让它做的与我想要的相反,但我无法解决它。

pattern = re.compile("@(MEDIA)|(CEO)|(EMPLOYEE)")
test = ["hello @CEO said the @user in the @MEDIA", "there is a new @EMPLOYEE said the @user"]
for t in test:
    test = [re.sub(pattern,"USER",t) for t in test]
test

>>>['hello @USER said the @user in the USER', 'there is a new @USER said the @user']

标签: pythonregex

解决方案


您可以使用

(?<!\S)@(?!COMPANY|CEO|MEDIA)\b[^@\s]+

模式匹配:

  • (?<!\S)@在左边断言一个空白边界,然后匹配@
  • (?!COMPANY|CEO|MEDIA)\b负前瞻,不直接断言任何替代方案的权利
  • [^@\s]+匹配除 @ 或 whitspace 字符之外的任何字符的 1 次以上。

查看正则表达式演示Python 演示

在替换中,您可以使用"@MENTION"

import re
pattern = re.compile(r"(?<!\S)@(?!COMPANY|CEO|MEDIA)\b[^@\s]+")
test = ["hello @CEO said the @user in the @MEDIA", "there is a new @EMPLOYEE said the @user"]
for t in test:
    test = re.sub(pattern, "@MENTION", t)
    print(test)

输出

hello @CEO said the @MENTION in the @MEDIA
there is a new @MENTION said the @MENTION

推荐阅读