1

I have the following string in R

A<-"A (23) 56 hh()"

I want to get the following output

"A (23) 56 hh"

I tried the following code

B<-gsub(pattern = "()", replacement = "", x = A)

That didnt yield the desired result. How can I accomplish the same

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
Raghavan vmvs
  • 1,213
  • 1
  • 10
  • 29
  • See - [How do I deal with special characters like \^$.?*|+()[{ in my regex?](https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex) – Ronak Shah Jul 30 '21 at 12:38

5 Answers5

5

Try fixed = TRUE in gsub

> gsub("()", "", A, fixed = TRUE)
[1] "A (23) 56 hh"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
5

Using str_remove

library(stringr)
str_remove_all(A, fixed("()"))

-ouptut

[1] "A (23) 56 hh"
akrun
  • 874,273
  • 37
  • 540
  • 662
4

try B<-gsub(pattern = "\\(\\)", replacement = "", x = A)

\\ indicates that it is a specific character - not the regex expression in brackets

dy_by
  • 1,061
  • 1
  • 4
  • 13
4

dy_by and ThomasIsCoding have good answers. Here is a modification of dy_by's answer

gsub(pattern = "\\()", replacement = "", x = A)

[1] "A (23) 56 hh"
TarJae
  • 72,363
  • 6
  • 19
  • 66
3

Another option defining removal of two consecutive parenthesis chars, which obviates the need for fixed=TRUE:

library(stringr)

A %>% str_remove("[()]{2}")

[1] "A (23) 56 hh"
GuedesBF
  • 8,409
  • 5
  • 19
  • 37