3

Can you extract these "key: value" pairs with ONE regex only?

"a: xyz   b:  pqr st  c: lm no p"

The result I would like:

"a" => "xyz"
"b" => "pqr st"
"c" => "lm no p"

My Attempt (With Two Regex)

var s = 'a: xyz   b:  pqr st  c: lm no p';
var r = /(?:.(?!(?:a|b|c):))+/g;
var m;

while ((m = r.exec(s))) {

    var s2 = m[0];
    var r2 = /(a|b|c):\s*(.+)/;
    var m2 = r2.exec(s2);

    console.log('"' + m2[1] + '" => "' + m2[2] + '"');
}

The result I get:

"a" => "xyz  "
"b" => "pqr st "
"c" => "lm no p"

So, can this be done with ONE regex only?

0

3 Answers 3

2

Use regex pattern /(\w+):\s*([^:]+)(?=\s|$)/g

See this demo.

To trim whitespace characters use around use regex pattern

/(\w+):\s*([^:]*\S)\s*(?=\w+:|$)/g

See this demo.

 /\b(\w+):\s*([^:]*\S)\b\s*(?=\w+:|$)/g

See this demo.

Sign up to request clarification or add additional context in comments.

5 Comments

Nope, doesn't get the "st" in b or the "no p" in c.
@GrantShield - Click on demo link again. Works for me!
@GrantShield - I have posted updated version that trim whitespace characters
Thanks, but if the key is longer than one char it doesn't work.
@GrantShield - Answer/Code has been updated based on your comment
2

You can try this

var s = 'a: xyz   b:  pqr st  c: lm no p';
var r = /(?:\s|^)(\w+):\s*(.*?)(?=\s+\w+:|$)/g;
var m;

while ((m = r.exec(s))) {
    console.log('"' + m[1] + '" => "' + m[2] + '"');
}

5 Comments

Almost perfect, thank you! Anyway to trim the whitespace in the values?
/(?:.(?!(?:a|b|c):))+\w/g The \w at the end will trim the whitespace.
This one allows multi char keys (which is great!) but there is white-space before some of the values. It it possible to trim that?
/(?:\s|^)(\w+):\s*(.*?)(?=\s+\w+:|$)/g;
Wrong! - I've posted correct code in the above comment 1 minute ago. Use that one!
0

Regex:

/(?:.(?!(?:a|b|c):))+\w/g

1 Comment

This one doesn't seem to capture any groups.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.