regex - 从R中的向量中提取子字符串

标签 regex r stringr

我正在尝试从非结构化文本中提取子字符串。例如,假设一个国家名称向量:

countries <- c("United States", "Israel", "Canada")

如何传递这个字符值向量以从非结构化文本中提取精确匹配。

text.df <- data.frame(ID = c(1:5), 
text = c("United States is a match", "Not a match", "Not a match",
         "Israel is a match", "Canada is a match"))

在此示例中,所需的输出为:

ID     text
1      United States
4      Israel
5      Canada

到目前为止,我一直在使用 gsub 来删除所有不匹配项,然后删除然后删除具有空值的行。我也一直在使用 stringr 包中的 str_extract ,但没有成功让正则表达式的参数正确。任何帮助将不胜感激!

最佳答案

1.字符串

我们可以首先使用“indx”(由折叠“国家”向量形成)作为“grep”中的模式来子集“text.df”,然后使用“str_extract”从“文本”中获取模式元素列,将其分配给子数据集的“文本”列(“text.df1”)

library(stringr)
indx <- paste(countries, collapse="|")
text.df1 <- text.df[grep(indx, text.df$text),]
text.df1$text <- str_extract(text.df1$text, indx)
text.df1
#  ID          text
#1  1 United States
#4  4        Israel
#5  5        Canada

<强>2。基础R

不使用任何外部包,我们可以删除'ind'以外的字符

text.df1$text <- unlist(regmatches(text.df1$text, 
                           gregexpr(indx, text.df1$text)))

3.字符串i

我们还可以使用 stringi

中更快的 stri_extract
library(stringi)
na.omit(within(text.df, text1<- stri_extract(text, regex=indx)))[-2]
#  ID         text1
#1  1 United States
#4  4        Israel
#5  5        Canada

关于regex - 从R中的向量中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196831/

相关文章:

python - python中的常量字符串加正则表达式

R-confusionMatrix()-sort.list(y) : 'x' must be atomic for 'sort.list' 中的错误

r - R 语言中的箭头/矢量表示法

r - 根据 R 中字符串变量的部分匹配进行过滤

r - 为什么 string::str_split 在 dplyr::mutate 时不更新数据帧

regex - 如何使用正则表达式验证电子邮件地址?

javascript - 我应该使用 Xpath 还是 regexp 来实现此目的?

mysql - LEFT JOIN 表和 REGEXP 特定字符的 SUM 值

r - 如何匹配R中两列之间的字符串?

R 将句子缩减为单词