R 在特定字符前提取2个术语

R 在特定字符前提取2个术语,r,stringr,stringi,R,Stringr,Stringi,我想提取Twitter@handle前面的两个单词 x <- c("this is a @handle", "My name is @handle", "this string has @more than one @handle") x您可以使用量词{2}指定要在字符@之前提取多少单词。单词由单词字符\\w+和单词边界组成,在您的情况下,边界是空格。我们可以使用trimws函数删除不必要的前导和尾随空格: library(stringr) lapply(str_extract_all(

我想提取Twitter@handle前面的两个单词

x <- c("this is a @handle", "My name is @handle", "this string has @more than one @handle")

x您可以使用量词
{2}
指定要在字符
@
之前提取多少单词。单词由单词字符
\\w+
和单词边界组成,在您的情况下,边界是空格。我们可以使用
trimws
函数删除不必要的前导和尾随空格:

library(stringr)
lapply(str_extract_all(x, "(\\w+\\s+){2}(?=@)"), trimws)

#[[1]]
#[1] "is a"

#[[2]]
#[1] "name is"

#[[3]]
#[1] "string has" "than one"

您可能需要
str\u split
library(stringr)
lapply(str_extract_all(x, "(\\w+\\s+){2}(?=@)"), trimws)

#[[1]]
#[1] "is a"

#[[2]]
#[1] "name is"

#[[3]]
#[1] "string has" "than one"