itthrill
itthrill

Reputation: 1376

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)"

Upvotes: 8

Views: 20060

Answers (3)

s_baldur
s_baldur

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

Martin Schmelzer
Martin Schmelzer

Reputation: 23879

Using the correct regex works:

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

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

Upvotes: 16

MKR
MKR

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

Related Questions