我有以下示例推文:
RT @user1: who are @thing and @user2?
我只想要user1、thing和user2,请问我可以使用什么正则表达式来提取这三个名称?
PS:用户名只能包含字母、数字和下划线。
经过测试:
/@([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
)
/(?<!\w)@(\w+)/
尝试使用迭代器(findall)和此正则表达式:
(@[\w-]+)
再见
twttr.txt.extractMentions("a very generic twitt with some @mention");
[1] https://github.com/twitter/twitter-text-js
[1] https://github.com/twitter/twitter-text-js 的链接。这应该可以解决问题(我使用了命名捕获以方便):
.+?@(?[a-zA-Z0-9_]+):[^@]+?@(?[^\s]+)[^@]+?@(?[a-zA-Z0-9_]+)