我有以下示例推文:
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
)
关于regex - 如何从推文中提取用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/740590/