r中的精确字符串匹配

Exact string matching in r

我在 R 中努力进行精确的字符串匹配。我只需要在句子中与搜索到的字符串进行精确匹配:

sentence2 <- "laptop is a great product"
words2 <- c("top","laptop")

我正在尝试这样的事情:

sub(paste(c("^",words2,"$")),"",sentence2)

而且我只需要用空字符串替换笔记本电脑 - 对于完全匹配(笔记本电脑)但没有用...

拜托,你能帮帮我吗?提前致谢。

期望的输出:

is a great product

你可以试试:

gsub(paste0("^",words2," ",collapse="|"),"",sentence2)
#[1] "is a great product"

paste0("^",words2," ",collapse="|")的结果是"^top |^laptop ",意思是"either 'top' at the beginning of string followed by a space or 'laptop' at the beginning of string followed by a space"。

如果你想匹配整个单词,那么你可以使用\b来匹配单词边界。

gsub(paste0('\b', words2, '\b', collapse='|'), '', sentence2)

## [1] " is a great product"

如果您还想替换相邻的空格,请在模式中添加可选的空格。

gsub(paste0('\s*\b', words2, '\b\s*', collapse='|'), '', sentence2)

## [1] "is a great product"