r - 如何在同一个正则表达式中搜索多个单词?

标签 r regex lapply gsub

我有一个特定单词列表来删除句子列表。我是否必须循环遍历列表并对每个正则表达式应用一个函数,或者我可以以某种方式一次性调用它们吗?我尝试过用 lapply 来做到这一点,但我希望找到更好的方法。

 string <- 'This is a sample sentence from which to gather some cool 
 knowledge'

 words <- c('a','from','some')

lapply(words,function(x){
  string <- gsub(paste0('\\b',words,'\\b'),'',string)
})

我想要的输出是: 这是收集酷知识的例句。

最佳答案

您可以使用正则表达式 OR 运算符("|")(有时称为“管道”符号)折叠要删除的单词的字符向量。

gsub(paste0('\\b',words,'\\b', collapse="|"), '', string)
[1] "This is  sample sentence  which to gather  cool \n knowledge"

或者:

gsub(paste0('\\b',words,'\\b\\s{0,1}', collapse="|"), '', string)
[1] "This is sample sentence which to gather cool \n knowledge"

关于r - 如何在同一个正则表达式中搜索多个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48967141/

相关文章:

r - 在预先排序的列上合并 R 中的数据框?

r - ggplot2:yearmon 比例和 geom_bar

r - 提取按条件过滤的值列表

R:将列表中的每个数据帧与数据帧中的不同列合并

python - 计算非常小的值的-log10

file-io - 如何在 R 中编写 CSV,并在 R 中保持矩阵名称 (dimnames(M)) 不变?

python - 如何在 Regex.Replace 中执行此操作?

正则表达式匹配日期,如月份名称日逗号和年份

regex - 随机生成器匹配正则表达式?

R递归获取任意深度嵌套列表的第一个元素的名称