Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - replace all odd numbered occurrences of a comma

If I have a string formatted like this:

"name", "bob", "number", 16, "place", "somewhere" 

And I want, instead, to have a string like this:

"name": "bob", "number": 16, "place": "somewhere" 

Also, the test cases do have some examples of strings like this:

"name", "bob", "hello, world", true

That would need to be formatted like this:

"name" : "bob", "hello, world" : true

...with every odd comma being replaced by a colon (so long as that comma falls outside of quotes), how on Earth would I do that via regex?

I've found the following regex via Google: /(,)(?=(?:[^"]|"[^"]*")*$)/,':' , which matches the first comma instance. How do I alternate every other one from there on out?

Edit for more info:

What I'm trying to do is take this string where each value is delineated by a comma and format it like a JS object using .replace(). So, in this case, "name", "number" and "place" represent key values. They're not fixed, this is simply an example.

like image 799
radicalsauce Avatar asked Aug 22 '14 03:08

radicalsauce


2 Answers

Regex:

,(.*?(?:,|$))

Replacement string:

:$1

DEMO

Example:

> '"name", "bob", "number", 16, "place", "somewhere" '.replace(/,(.*?(?:,|$))/g, ':$1');
'"name": "bob", "number": 16, "place": "somewhere" '

Update:

If the field names are comma seperated then you could try the below regex,

> '"name", "bob", "hello, world", true'.replace(/("(?:\S+?|\S+ \S+)"), ("[^"]*"|\S+)/g, '$1: $2');
'"name": "bob", "hello, world": true'
like image 104
Avinash Raj Avatar answered Nov 06 '22 07:11

Avinash Raj


You can go with this Regular Expression that covers all matches together.

(?=(?:[^"]*"[^"]*")*[^"]*$)(,)(.*?,|)(?=.*?(?:,|$))

Replacement is: :$2

Live demo

like image 28
revo Avatar answered Nov 06 '22 08:11

revo