If you have no other digits in your strings a lookaround is not needed. If you do however, especially in the context of (
and )
, then lookaround, specifically negative lookbehind, is needed:
gsub("(?<!\\()\\s?\\d+\\)", "", strings, perl = TRUE)
[1] "Gmünd" "Hermagor" "Tegernsee (4)" "Some (stuff) 444"
How this works:
(?<!\\()
negative lookbehind to assert that there is not a literal (
immediately prior to ...
\\s?\\d+\\)
... an optional space, followed by one or more digits, followed by a literal )
Data:
strings <- c("Gmünd 5) 6) 7)", "Hermagor 3)", "Tegernsee (4)", "Some (stuff) 444")