如何在R中使用正则表达式从文本字符串中提取Twitter用户名?
我试过了
library(stringr)
theString <- '@foobar Foobar! and @foo (@bar) but not [email protected]'
str_extract_all(string=theString,pattern='(?:^|(?:[^-a-zA-Z0-9_]))@([A-Za-z]+[A-Za-z0-9_]+)')
但是,我最后得到@foobar
,@foo
并且(@bar
其中包含不需要的括号。
我怎样才能得到公正@foobar
,@foo
并@bar
作为输出?
这是一种适用于的方法R
:
theString <- '@foobar Foobar! and @foo (@bar) but not [email protected]'
theString1 <- unlist(strsplit(theString, " "))
regex <- "(^|[^@\\w])@(\\w{1,15})\\b"
idx <- grep(regex, theString1, perl = T)
theString1[idx]
[1] "@foobar" "@foo" "(@bar)"
如果您想在中使用@Jerry的答案R
:
regex <- "@([A-Za-z]+[A-Za-z0-9_]+)(?![A-Za-z0-9_]*\\.)"
idx <- grep(regex, theString1, perl = T)
theString1[idx]
[1] "@foobar" "@foo" "(@bar)"
但是,这两种方法都包含不需要的括号。
更新这将使您开始时没有括号或任何其他标点符号(下划线除外,因为用户名中允许使用下划线)
theString <- '@foobar Foobar! and @fo_o (@bar) but not [email protected]'
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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句