admin管理员组

文章数量:1334826

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 ma being replaced by a colon (so long as that ma 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 ma 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 ma 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.

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 ma being replaced by a colon (so long as that ma 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 ma 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 ma 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.

Share Improve this question edited Aug 22, 2014 at 3:54 radicalsauce asked Aug 22, 2014 at 3:21 radicalsauceradicalsauce 716 bronze badges 10
  • Can you use a custom callback for the replacement? – alex Commented Aug 22, 2014 at 3:23
  • @alex - Could you clarify what you mean by that in this context? – radicalsauce Commented Aug 22, 2014 at 3:24
  • Are the "name", "number", "place"... entries from a fixed set? – Freiheit Commented Aug 22, 2014 at 3:24
  • What language are you using? – Andrew Whitaker Commented Aug 22, 2014 at 3:25
  • Which language do you use and why not String operations? – thefourtheye Commented Aug 22, 2014 at 3:25
 |  Show 5 more ments

6 Answers 6

Reset to default 3

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 ma 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'

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

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

Replacement is: :$2

Live demo

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

it has to be applied once. otherwise every but the last one , will bees :.

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

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

This works for all cases.

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

The first part of the regex "[^"]+" captures the name under quotes: "name" or "hello, world".

The second part of the regex ("[^"]+"|[^",]+) captures either a name under quotes or a string without quote or ma: "bob" or true.

Ok here's an updated answer that (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/w9eghqmy/1

本文标签: javascriptRegexreplace all odd numbered occurrences of a commaStack Overflow