从R中的twitter状态中提取用户。非常重要的情况,如RT @ user @user:

时间:2015-06-27 18:40:29

标签: regex r grepl

我想从推文中提取用户名,这些用户名可能是:

  • 后跟一些非字母数字字符。
  • 之前没有空格。

例如,从中:

"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."

我该怎么做呢?

2 个答案:

答案 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"