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

标签 regex twitter

我有以下示例推文:

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/

相关文章:

php - 正则表达式中的 "~"是什么?

c# - 在 * 字符正则表达式上拆分字符串

java - 给定一个字符串,在第 50 个位置插入一个新的换行符并排除整个单词

php - 如何在 mysql 查询中使用正则表达式?

python - 尝试在 Python 中解析 JSON。值错误 : Expecting property name

基于 Java 的语法检查/基于规则的工具集

python - tweepy.Cursor 一遍又一遍地返回相同的用户

android - 适用于 Android 的 Twitter,例如左右滑动快捷菜单

java - 清洁数据推文

url - FB、TWITTER、G+ 分享网址和固定预览图像