0

I have a CSV line, that looks like:

foo, bar, baz, "england, scotland, wales, ireland", sith

and need to convert it into

"foo", "bar", "baz", "england, scotland, wales, ireland", "sith"

I've decided to replace all commas between double quotes with 'comma', but after picking up a substirng between the double quotes I have a problem with regex to do so, because while using a

replace(/(.+)(,)(.+)/g, "'comma'")

I take next substring

"england, scotland, wales'comma' ireland"

instead of

"england'comma' scotland'comma' wales'comma' ireland"

I don't want to use regex with more complicated structure like

/(.+)(,)(.+)(,)(.+)(,)(.+)/g

and wish to group word with comma sign but can't pick a right regex for it, so I use a recursive substring search with match in for loop. Am I doing right, or there is a regex that fits but I haven't find it yet. Thank you.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
glebovJs
  • 11
  • 4
  • 4
    don't use regex, use a [CSV parser](http://stackoverflow.com/a/12785546/497418). – zzzzBov Oct 09 '14 at 20:19
  • this is probably pushing the boundaries of being an opinionated question, but I'd also avoid regex in this case, as you will end up with something that's at best hard to read, at worst, a maintainability nightmare. – user2366842 Oct 09 '14 at 20:21
  • `replace(/(.+)(,)(.+)/g, "'comma'")` seems unclear. Why are you trying to replace with comma? – Avinash Raj Oct 09 '14 at 20:23
  • Your best bet is to use a split function that supports regex. –  Oct 09 '14 at 20:58

1 Answers1

2

You can use this pattern:

var re = /"([^"]*)"|([^\s,][^,]*)/g;
var str = 'foo, bar, baz, "england, scotland, wales, ireland", sith';
var subst = '"$1$2"';

var result = str.replace(re, subst);

console.log(result);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125