0

I've got a character in R:

value <- "This is (delete) a (keep) test sentence."

I want to remove the first pair of parentheses with the text, but keep the second one. I tried to use a gsub():

value2 <- gsub("(delete)", " ", value)

The result is: "This is () a (keep) test sentence."

But what I need is: "This is a (keep) test sentence."

What can I do to reach this?

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Tomster
  • 11
  • 2

1 Answers1

1

Use sub :

sub('\\(.*?\\)\\s', '', value)
#[1] "This is a (keep) test sentence."
  • () are metacharacters and need to be escaped with \\.

  • .*? is to match as few characters possible till a closing bracket ()) is encountered.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213