1

I have a string with brackets which I want to remove. I tried:

L0 <- c("(ABC)","DEF","GHI","J(K)")

L1  <- gsub( '()',"",L0)
L1  <- gsub( '(',"",L0)
L1  <- gsub( '(',"",L0)

L1

But this did not work.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
adam.888
  • 7,686
  • 17
  • 70
  • 105

1 Answers1

4

We can use a single gsub to remove the bracket. Place it in square bracket to evaluate it literally.

gsub("[()]", "", L0)
#[1] "ABC" "DEF" "GHI" "JK" 

There is also an option fixed = TRUE. In that case

gsub("(", "", L0, fixed = TRUE) # remove the `(`
gsub(")", "", L0, fixed = TRUE) # remove the `)`

and for both

gsub("(", "", gsub(")", "", L0, fixed = TRUE), fixed = TRUE)
#[1] "ABC" "DEF" "GHI" "JK" 

The issue is that when we use (), it implies a meaning i.e. to capture some groups. For example in the following code, we remove substring and capture the second character

sub("^.(.).*", "\\1", L0)
#[1] "A" "E" "H" "("
akrun
  • 874,273
  • 37
  • 540
  • 662