Reputation: 1376
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)"
Upvotes: 8
Views: 20060
Reputation: 33498
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"
Upvotes: 2
Reputation: 23879
Using the correct regex works:
gsub("[()]", "", "(abc)")
The additional square brackets mean "match any of the characters inside".
Upvotes: 16
Reputation: 20085
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 `)`
Upvotes: 1