在R中使用Regex获取Twitter @Username

时间:2013-08-10 18:03:11

标签: regex r twitter

如何在R中使用regex从一串文本中提取Twitter用户名?

我试过

library(stringr)

theString <- '@foobar Foobar! and @foo (@bar) but not foo@bar.com'

str_extract_all(string=theString,pattern='(?:^|(?:[^-a-zA-Z0-9_]))@([A-Za-z]+[A-Za-z0-9_]+)')

但我最终得到@foobar@foo(@bar,其中包含不需要的括号。

如何才能将@foobar@foo@bar作为输出?

3 个答案:

答案 0 :(得分:7)

这是一种适用于R的方法:

theString <- '@foobar Foobar! and @foo (@bar) but not foo@bar.com'
theString1 <- unlist(strsplit(theString, " "))
regex <- "(^|[^@\\w])@(\\w{1,15})\\b"
idx <- grep(regex, theString1, perl = T)
theString1[idx]
[1] "@foobar" "@foo"    "(@bar)"

如果您想在R中使用@Jerry的答案:

regex <- "@([A-Za-z]+[A-Za-z0-9_]+)(?![A-Za-z0-9_]*\\.)"
idx <- grep(regex, theString1, perl = T)
theString1[idx]
[1] "@foobar" "@foo"    "(@bar)" 

但是,这两种方法都包含您不想要的括号。

UPDATE 这将从头到尾没有括号或任何其他类型的标点符号(除了下划线,因为它们在用户名中被允许)

theString <- '@foobar Foobar! and @fo_o (@bar) but not foo@bar.com'
theString1 <- unlist(strsplit(theString, " "))
regex1 <- "(^|[^@\\w])@(\\w{1,15})\\b" # get strings with @
regex2 <- "[^[:alnum:]@_]"             # remove all punctuation except _ and @
users <- gsub(regex2, "", theString1[grep(regex1, theString1, perl = T)])
users

[1] "@foobar" "@fo_o"   "@bar"

答案 1 :(得分:1)

尝试使用负面的lookbehind,以便在匹配中不消耗字符:

(?:^|(?<![-a-zA-Z0-9_]))@([A-Za-z]+[A-Za-z0-9_]+)
      ^^^
编辑:因为看起来外观在R中不起作用(我在这里发现某个地方看起来在R上起作用,但显然不是......),试试这个:

@([A-Za-z]+[A-Za-z0-9_]+)(?![A-Za-z0-9_]*\\.)

编辑:双重转义点

EDITv3 ...:尝试打开PCRE:

str_extract_all(string=theString,perl("(?:^|(?<![-a-zA-Z0-9_]))@([A-Za-z]+[A-Za-z0-9_]+)")

答案 2 :(得分:1)

@[a-zA-Z0-9_]{0,15}

位置:

  • @从字面上匹配字符@(区分大小写)。

  • [a-zA-Z0-15]匹配列表中存在的单个字符

  • {0,15}量词匹配0到15次,最多匹配 可能,根据需要退还

从混合数据集中选择Twitter用户名的效果很好。