简体   繁体   中英

Removing/replacing brackets from R string using gsub

I want to remove or replace brackets "(" or ")" from my string using gsub. However as shown below it is not working. What could be the reason?

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

Using the correct regex works:

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

The additional square brackets mean "match any of the characters inside" .

A safe and simple solution that doesn't rely on regex:

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

The possible way could be (in the line OP is trying) as:

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM