3

I would like to replace all commas in a comma-delimited string with a pipe ('|') except for those that are found in double quotes. I would prefer to use the JavaScript "replace" function if possible.

My regex knowledge is limited at best. I am able to replace all commas with pipes, but that does not give me the desired result for parsing through the data. I also found a regex on here that removed all commas except those in quotations, but does not implement a pipe or some other delimiter.

(?!\B"[^"]*),(?![^"]*"\B)

Here is an example of what I'm trying to accomplish:

string1 = 1234,Cake,,"Smith,John",,"Status: Acknowledge,Accept",,Red,,

and I would like it to look like:

string1 = 1234|Cake||"Smith,John"||"Status: Ackknowledge,Accept"||Red||
AC_Slater
  • 39
  • 1
  • 1
    That looks like CSV data. What happens when you want a literal `"` or newline? You're better off with a proper CSV parser. – OrangeDog Jun 09 '19 at 15:59

2 Answers2

3

One option is to use a replace callback to replace either a quote or a comma with the quote itself or a pipe respectively:

str = `1234,Cake,,"Smith,John",,"Status: Acknowledge,Accept",,Red,,`;

res = str.replace(/(".*?")|,/g, (...m) => m[1] || '|');

console.log(res)

Another (and IMO better in the long run) would be to use a dedicated parser to work with CSV data. CSV is actually trickier than it looks.

georg
  • 211,518
  • 52
  • 313
  • 390
1

We can simply capture our desired commas using alternation with a simple expression such as:

(".+?")|(,)

Demo

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
  • 2
    this seems to create an extra pipe for each comma – georg Jun 09 '19 at 15:25
  • 2
    (For each quoted string, actually. Add `,?` to the end of the left?) – Ry- Jun 09 '19 at 15:25
  • 2
    When running this with global substituation, I get the following result: 1234|Cake||||||||Red|| When I would expect: 1234|Cake||"Smith,John"||"Status: Ackknowledge,Accept"||Red|| – AC_Slater Jun 09 '19 at 17:07