我想从推文中提取用户名,这些用户名可能是:
例如,从中:
"RT@user1: This is a retweet that mentions @user2."
我想得到像
这样的矢量[1] @user1 @user2
(有或没有" @")
这是我目前的剧本:
text <- "RT@user1: This is a retweet that mentions @user2."
tokens <- unlist(strsplit(text, " "))
mentions.mask <- grepl("@\\w+", tokens)
mentions <- tokens[mentions.mask]
cat(mentions)
[1] "RT@user1:" "@user2."
我该怎么做呢?
答案 0 :(得分:3)
如果我理解得很好,这看起来非常简单,你的正则表达式只是缺少捕获组。你可以使用这个正则表达式:
(@\w+)
^----^--- Note capturing groups
<强> Working demo 强>
在R中你可以使用:
library(stringr)
str_extract("RT@user1: This is a retweet that mentions @user2.", "@\\w+")
答案 1 :(得分:1)
你可以坚持使用基础R。
text <- "RT@user1: This is a retweet that mentions @user2."
regmatches(text, gregexpr('@\\w+', text))[[1]]
# [1] "@user1" "@user2"
没有前面的@
:
regmatches(text, gregexpr('@\\K\\w+', text, perl=T))[[1]]
# [1] "user1" "user2"