Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove all numbers followed by parenthese with Regex in R (use negative lookaheads?!)

I want to remove all numbers that are immediately followed by a ).
My Strings look like this:

Gmünd 5) 6) 7)
Hermagor am See 3)

So I’d like to have the result:

Gmünd
Hermagor

I think the solution must involve negative lookaheads, but I am not really sure how to do that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"

Data:

strings <- c("Gmünd 5) 6) 7)", "Hermagor 3)", "Tegernsee (4)", "Some (stuff) 444")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading