[英]gsub: replace word if not wrapped in brackets
我想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
将查找一个单词,但带有否定的后视?<!
和负面展望?!
,单词边界不应该是[]
。 你也可以参考这个答案。
我们可以使用grep
轻松做到这一点
x[grep("^[^[]+$", x)] <- "test"
x
#[1] "test" "[hello]"
或与sub
sub("^[^[]+", "test", x)
#[1] "test" "[hello]"
对于第二种情况
sub("^\\b[^[+]+\\b", "test", x1)
#[1] "test [hello]"
x <- c("hello","[hello]")
x1 <- "hello [hello]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.