Regex - replace all odd numbers with comma

If I have a string formatted as follows:

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

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

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

In addition, in the test examples there are several examples of such lines:

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

This needs to be formatted as follows:

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

... when replacing each odd comma with a colon (as long as this comma goes beyond the quotes) , how on earth will I do this through regular expression?

I found the following regex via Google: /(,)(?=(?:[^"]|"[^"]*")*$)/,':' Which matches the first instance of the comma. How can I alternate each other?

Edit for more information:

What I'm trying to do is take this line where each value is defined by a comma and formats it as a JS object using .replace() . Thus, in this case, β€œname”, β€œnumber” and β€œplace” are key values. They are not fixed, this is just an example.

+6
source share
6 answers

You can go with this regex that covers all matches.

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

Replacement :$2

Live demo

+1
source

Regex:

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

Replaced 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 separated by a comma, you can try the following regular expression,

 > '"name", "bob", "hello, world", true'.replace(/("(?:\S+?|\S+ \S+)"), ("[^"]*"|\S+)/g, '$1: $2'); '"name": "bob", "hello, world": true' 
+2
source

substitude ([^,]+),([^,]+,) to \1:\2 apply it once, globally.

it should be applied once. otherwise everyone, except the last, will become :.

0
source

Well here is the updated answer: (ab) uses JSON.parse and JSON.stringify :

 function formatString(input) { var arr = JSON.parse('[' + input + ']'), result = '', i; for (i = 0; i < arr.length; i++) { result += JSON.stringify(arr[i]); if (i !== arr.length - 1) { if (i % 2 === 0) { result += ': '; } else { result += ', '; } } } return result; } 

Example: http://jsfiddle.net/w9eghqmy/1

0
source
  "(.*?)(?<=\")(\s*)\,(\s*)(\S+)" 

Replace with "\ 1 \ 2: \ 3 \ 4"

This works for all cases.

0
source
 var str='"name", "bob", "hello, world", true'; str.replace(/("[^"]+"), ("[^"]+"|[^",]+)/g,"$1: $2"); 

The first part of the regular expression "[^"]+" captures the name under quotation marks:" name "or" hello world. "

The second part of the regular expression ("[^"]+"|[^",]+) captures either the name under quotation marks or a string without a quote or comma: "bob" or true.

0
source

Source: https://habr.com/ru/post/974192/


All Articles