Regex to remove commas in string if criteria are met in R

Viewed 368

I would like to remove commas from a list of addresses if 1) the comma follows any number or 2) the comma follows a number with a single letter.

So if my input looked like this:

library("data.table")
Input <- data.table(Var = c("43, Badger Drive", "45A, Badger Drive",
                            "45BB, Badger Drive", "Zebra House, 200A Badger Drive", 
                            "F27, 20 Badger Drive", "78, Badger 24 Drive"))

My output would look like this:

Output <- data.table(Var = c("43 Badger Drive", "45A Badger Drive", 
                            "45BB, Badger Drive"," Zebra House, 200A Badger Drive", 
                            "F27, 20 Badger Drive", "78 Badger 24 Drive"))

This almost achieves my first criteria, but removes the comma on line 5 after F27, nor am I sure how it can be modified to achieve my second criteria:

Input[, New_Input := gsub("([[:digit:]]),", "\\1", Input$Var)]
1 Answers

You can use

gsub("([[:digit:]][[:alpha:]]?),", "\\1", Input$Var)

Here,

  • ([[:digit:]][[:alpha:]]?) - Capturing group 1: a digit and an optional letter
  • , - a comma

The match is only replaced with the Group 1 contents, so the comma is only removed when it is immediately preceded with a digit or a digit+letter.

See the regex demo.

Related