如何从推文中提取用户名?

8

我有以下示例推文:

RT @user1: who are @thing and @user2?

我只想要user1thinguser2,请问我可以使用什么正则表达式来提取这三个名称?

PS:用户名只能包含字母、数字和下划线。

5个回答

18

经过测试:

/@([a-z0-9_]+)/i
在 Ruby (irb) 中:
>> "RT @user1: who are @thing and @user2?".scan(/@([a-z0-9_]+)/i)
=> [["user1"], ["thing"], ["user2"]]

在Python中:

>>> import re
>>> re.findall("@([a-z0-9_]+)", "RT @user1: who are @thing and @user2?", re.I)
['user1', 'thing', 'user2']

在PHP中:

<?PHP
$matches = array();
preg_match_all(
    "/@([a-z0-9_]+)/i",
    "RT @user1: who are @thing and @user2?",
    $matches);

print_r($matches[1]);
?>

Array
(
    [0] => user1
    [1] => thing
    [2] => user2
)

您需要在 [a-z0-9_] 周围添加一个捕获组,即 @([a-zA-Z0-9_]+)。 - Martin C.
谢谢,它很好用!最后一个问题:当“@”符号前必须有空格或者在开头时,我能使用以下表达式吗? "/( |^)@([a-z0-9_]+)/i" - caw
你也可以使用单词边界 \b => /\b@([a-z0-9_]+)/i - Stefan Gehrig

2
/(?<!\w)@(\w+)/

上述内容涵盖了其他回答中没有的以下情况:
  • 一个不应该被视为用户名的@符号,例如“我的电子邮件是test@example.com”
  • 仍然允许用户名出现在字符串开头,例如“@username lorem ipsum…”

谢谢。没有其他人考虑过电子邮件地址的问题! - innonate

2

尝试使用迭代器(findall)和此正则表达式:

(@[\w-]+)

再见


简单...不错!结合 scan(Ruby)使用以获取匹配项数组:text.scan(/ @ [\ w-] + /) - Danny

1

0

这应该可以解决问题(我使用了命名捕获以方便):

.+?@(?[a-zA-Z0-9_]+):[^@]+?@(?[^\s]+)[^@]+?@(?[a-zA-Z0-9_]+)


当我使用您的表达式时,PHP会显示错误消息。类似于“缺少分隔符.在结尾处”之类的信息。 - caw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接