1

I want to extract usernames from a tweet where these usernames may be:

  • followed by some non-alphanumerical characters.
  • not preceded by a white space.

For instance, from this:

"RT@user1: This is a retweet that mentions @user2."

I would like to get a vector like

[1] @user1 @user2

(with or without the "@")

This is my current script:

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

How can I do it properly?

4

2 回答 2

5

如果我理解得很好,这似乎很简单,您的正则表达式只是缺少捕获组。您可以使用此正则表达式:

(@\w+)
^----^--- Note capturing groups

工作演示

在 R 中,您可以使用:

library(stringr)
str_extract("RT@user1: This is a retweet that mentions @user2.", "@\\w+")
于 2015-06-27T19:36:08.897 回答
2

你可以简单地坚持使用base 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"
于 2015-06-27T20:51:28.933 回答