grep 和 gsub 查找模式并调出模式

grep and gsub to find patterns and call out patterns

我正在尝试在文本中搜索关键字,然后提取找到的关键字。

现在我在/可重现的例子:

text <- c("Here is some text about cats and dogs",
          "Here is some text about turtles and chickens",
          "Here is some text about rhinos and elephants")
pattern <- "cat|turtle"
HasPattern <- as.vector(NULL)
for(i in 1:length(text)){
if(sum(grepl(pattern, text[i], ignore.case = TRUE)>0))
   HasPattern <- append(HasPattern, text[i])
}

此输出的预期结果为:

gsub(grepl(pattern, text), pattern, text) # or something
[1] cat turtle NA

我试过了 --

for (i in 1:length(text)){
  if(grepl(pattern, text[i]) == TRUE)
     gsub(text[i], pattern, text[i])
}


sub(text, pattern, text)

gsub(grepl(pattern, text), pattern, text)

在可重现的例子中: HasPattern 给了我一个包含我想要的文本的向量,这很棒。但我也想要一个向量,说明它在这些文本中发现了什么模式。

我们可以使用str_extract

library(stringr)
str_extract(text, pattern)
#[1] "cat"    "turtle" NA      

您还可以在 baseR

中执行 regmatchesgregexpr
regmat <- regmatches(text,gregexpr(pattern,text))
regmat[lapply(regmat , length) == 0] <- NA 
unlist(regmat)

输出:

> unlist(regmat)
[1] "cat"    "turtle" NA