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.
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.
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" "("