orange
orange

Reputation: 8090

Regex missing to capture last key-value list entry

I have a string such as this one:

a=func(1, 2, 2), b='hey', c=foobar('text'), d=1

which I'd like to parse into its key-value components, so that I can obtain a list of

[['a', 'func(1, 2, 2)', ['b', '\'hey\''], ['c', 'foobar(\'text\')'], ['d', '1']]

My approach was to use this regex: (\w*) *= *([^=]*), (?=\w* *=) with a positive lookahead, but that's ignoring the last key-value pair (d=1). Any idea how I can make the positive lookahead optional?

Upvotes: 1

Views: 182

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521609

Try using the regex pattern (\w+)=(.*?)(?:,\s*(?=\w+=)|$), and then capture all matches:

var input = "a=func(1, 2, 2), b='hey', c=foobar('text'), d=1";
var regex = /(\w+)=(.*?)(?:,\s*(?=\w+=)|$)/g;
var match = regex.exec(input);
var result = [];
while (match != null) {
    result.push(new Array(match[1], match[2]));
    match = regex.exec(input);
}
console.log(result);

Here is what the pattern does:

(\w+)               match AND capture a key
=                   match an =
(.*?)               then match AND capture anything, until we see
(?:,\s*(?=\w+=)|$)  a comma, followed by optional space, and the next key
                    OR the end of the input string

Then, we build your expected 2D array using the first capture group as the key, and the second capture group as the value.

Upvotes: 2

Related Questions