gpt4 book ai didi

r - gsub : replace word if not wrapped in brackets

转载 作者:行者123 更新时间:2023-12-01 00:35:34 24 4
gpt4 key购买 nike

我要gsub一个词,但仅限于没有用括号括起来的情况。

x <- c("hello","[hello]")

我要 gsub(regex,"test",x)返回 c("test","[hello]") ,但我无法创建正确的正则表达式语句。

一个简单的实现是: gsub("^(?!\\[).*$","test",x, perl=TRUE) ,在上述情况下有效,但只是因为每个字符串是一个单词,所以它不适用于 x <- "hello [hello]"例如,我想成为 test [hello] .

我已经尝试了一堆不同的前瞻无济于事。任何帮助,将不胜感激。

输入
x <- c("hello", "[hello]", "hello [hello]")

想要的
# [1] "test"         "[hello]"      "test [hello]"

最佳答案

您可以使用负环视来设置对单词边界的约束,例如 (?<!\\[)\\b\\w+\\b(?!\\])仅当单词边界不是 [] 时才会替换单词:

gsub("(?<!\\[)\\b\\w+\\b(?!\\])", "test", x, perl = TRUE)
# [1] "test [hello]" # assuming this is your desired output
\\b\\w+\\b将寻找一个词,但具有否定的后视 ?<!和负面预测 ?! ,单词边界不应该是 [] .您也可以引用 this answer .

关于r - gsub : replace word if not wrapped in brackets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509498/

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