Removing/replacing brackets from R string using gsub
11,436
Solution 1
Using the correct regex works:
gsub("[()]", "", "(abc)")
The additional square brackets mean "match any of the characters inside".
Solution 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"
Solution 3
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 `)`
Author by
itthrill
During the weekdays I am a financial risk manager. Recent python enthusiast, trying to quit SAS and cigarettes.
Updated on July 18, 2022Comments
-
itthrill almost 2 years
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)"