r - 如何删除字符中带有文本的一对括号?
r - How can I remove a single pair of parentheses with text in a character?
我在R中有一个角色:
value <- "This is (delete) a (keep) test sentence."
我想删除带有文本的第一对括号,但保留第二对。我尝试使用 gsub()
:
value2 <- gsub("(delete)", " ", value)
结果是:"This is () a (keep) test sentence."
但我需要的是:"This is a (keep) test sentence."
我该怎么做才能达到这个目标?
使用sub
:
sub('\(.*?\)\s', '', value)
#[1] "This is a (keep) test sentence."
()
是元字符,需要用\
.
转义
.*?
是匹配尽可能少的字符,直到遇到右括号 ()
)。
我在R中有一个角色:
value <- "This is (delete) a (keep) test sentence."
我想删除带有文本的第一对括号,但保留第二对。我尝试使用 gsub()
:
value2 <- gsub("(delete)", " ", value)
结果是:"This is () a (keep) test sentence."
但我需要的是:"This is a (keep) test sentence."
我该怎么做才能达到这个目标?
使用sub
:
sub('\(.*?\)\s', '', value)
#[1] "This is a (keep) test sentence."
转义()
是元字符,需要用\
..*?
是匹配尽可能少的字符,直到遇到右括号 ()
)。