使用向量而不是 R 中的正则表达式从字符串中删除多个单词

Ray*_*oro 4 string r vector stringr

我想从 R 中的字符串中删除多个单词,但想使用字符向量而不是正则表达式。

例如,如果我有字符串

"hello how are you" 
Run Code Online (Sandbox Code Playgroud)

并想删除

c("hello", "how")
Run Code Online (Sandbox Code Playgroud)

我会回来

" are you"
Run Code Online (Sandbox Code Playgroud)

我可以近距离接触str_remove()来自stringr

"hello how are you" %>% str_remove(c("hello","how"))
[1]  "how are you"   "hello  are you"
Run Code Online (Sandbox Code Playgroud)

但我需要做一些事情来将其分解为一个字符串。是否有一个函数可以一次调用完成所有这些操作?

akr*_*run 5

我们可以使用|正则表达式来评估或

library(stringr)
library(magrittr)
pat <- str_c(words, collapse="|")
"hello how are you" %>% 
      str_remove_all(pat) %>%
      trimws
#[1] "are you"
Run Code Online (Sandbox Code Playgroud)

数据

words <- c("hello", "how")
Run Code Online (Sandbox Code Playgroud)

  • 改进建议:paste+collapse = "|" 在单词向量上..所以你不必重新输入所有内容? (2认同)