我有一个特定单词列表来删除句子列表。我是否必须循环遍历列表并对每个正则表达式应用一个函数,或者我可以以某种方式一次性调用它们吗?我尝试过用 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/