0

I have strings and would like to replace a pattern like (+ 1) (i.e. space, opening bracket, 1-3 digits, closing bracket.

for the string str1 <- "6 (+1010)", str2 <- "1 (+1)":

gsub("\\(\\+\\d{1,4}\\)", "", str1)
> "6 "
gsub("\\(\\+\\d{1,4}\\)", "", str2)
> "1 "

This works fine but still contains the trailing space; trying to address this, I have tried the following regexs without success:

  • gsub("\\(\\+\\d{1,4}\\) ", "", str1),
  • gsub("\\(\\+\\d{1,4}\\)\\s", "", str1),
  • gsub("\\(\\+\\d{1,4}\\)[[:space:]]", "", str1),

They all yield "6 (+1)". For now I am going with another, separate gsub() call but I'm sure there must be another, better way.

I am expecting the output 6 (without trailing space).

Ivo
  • 3,890
  • 5
  • 22
  • 53

0 Answers0