-2

I have this issue with address data in a terrible format. The last three comma separated data is ,city, country, postal code. But prior to the city, country, postal code parsed data the address has a couple of commas.

Example:

123 Oak St.,Appt 3,Suite 15,Paris,France,1234342

243 Oak St. Apt 4,New York,United States,12345

I would like to put a double quote before the third comma.

Line this:

123 Oak St.,Appt 3,Suite 15",Paris,France,1234342

243 Oak St. Apt 4",New York,United States,12345

Then I can insert a double quote at the begin as such.

Find: \r\n

Replace: \r\n"

Final output:

"123 Oak St.,Appt 3,Suite 15",Paris,France,1234342

"243 Oak St. Apt 4",New York,United States,12345

Any help with this problem is greatly appreciated.

Alan
  • 31
  • 3
  • Which regex engine/language? Also how do you identify a city? – ctwheels Oct 16 '20 at 18:36
  • Maybe [this](https://regex101.com/r/jI2ecE/1) works for you: `^|^([^,]*?(?:,[^,]*){0,2}?)(?=,\D+,)` with replacement of `$1"` – ctwheels Oct 16 '20 at 18:42
  • 1
    You could use `(?=(?:,[^,]*){3}$)`, replace with `"`. – Charlie Armstrong Oct 16 '20 at 18:43
  • Using Perl based regular expression syntax. – Alan Oct 16 '20 at 18:45
  • All the responses where helpful. I ended up using a part of ctwheels and Soc's responses to edit the file. Since I and not good at coding. :( I used the variant below. Find: ^(.+)(?=(,[^,]*){3}$) Replace: "$1" Thanks for the help. – Alan Oct 19 '20 at 14:46

1 Answers1

0

You can do this with Regex in JavaScript with the following example.

The important part is the look-ahead (?=(,[^,]*){3}$) means that the line must end with three comma groups. The first capture group (.*) matches everything before that.

Once you have this capture group you can wrap it up in double quotes with input.replace(expression, '"$1"').

const input = '123 Oak St.,Appt 3,Suite 15,Paris,France,1234342\n243 Oak St. Apt 4,New York,United States,12345';
const expression = /^(.+)(?=(,[^,]*){3}$)/gm;

console.log(input.replace(expression, '"$1"'));
Soc
  • 5,238
  • 3
  • 10
  • 25