Removing/replacing 使用 gsub 来自 R 字符串的括号

Removing/replacing brackets from R string using gsub

我想使用 gsub 从我的字符串中删除或替换方括号“(”或“)”。但是,如下所示,它不起作用。可能是什么原因?

 >  k<-"(abc)"
 >  t<-gsub("()","",k)
 >  t 
[1] "(abc)"

使用正确的正则表达式有效:

gsub("[()]", "", "(abc)")

额外的方括号表示"match any of the characters inside".

可能的方法是(在 OP 正在尝试的行中):

gsub("\(|)","","(abc)")
#[1] "abc"


`\(`  => look for `(` character. `\` is needed as `(` a special character. 
`|`  =>  OR condition 
`)` =   Look for `)`

不依赖正则表达式的安全简单的解决方案:

k <- gsub("(", "", k, fixed = TRUE) # "Fixed = TRUE" disables regex
k <- gsub(")", "", k, fixed = TRUE)
k
[1] "abc"