[英]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.