8

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)"
zx8754
  • 52,746
  • 12
  • 114
  • 209
itthrill
  • 1,241
  • 2
  • 17
  • 36

3 Answers3

16

Using the correct regex works:

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

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

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
2

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"
s_baldur
  • 29,441
  • 4
  • 36
  • 69
1

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 `)`
MKR
  • 19,739
  • 4
  • 23
  • 33