gpt4 book ai didi

regex - r 中的精确字符串匹配

转载 作者:行者123 更新时间:2023-12-02 15:18:35 25 4
gpt4 key购买 nike

我在 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 " 这意味着“要么 ' top' 在字符串开头,后跟一个空格或 'laptop' 在字符串开头,后跟一个空格”。

关于regex - r 中的精确字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com