0

how can I make a regex to parse this string ?

"desc: random text string, sender: James, se-status: red, problem-field: I'm a problem field, I'm a problem field, action: runs, target: John, ta-status: blue, status-apply: red, lore: lore ipsum dolor sit amet"

I want groups that get keys and values. Please note the "problem-field" has quotes in it. The groups should get the key and then locate the last comma before the next key name.

This is an example string. Other strings can have different field names, so the regex shouldn't match specific field names like sender or action.

expected result groups:

1. "desc"
2. "random text string"
3. "sender"
4. "James"
5. "se-status"
6. "red"
7. "problem-field"
8. "I'm a problem field, I'm a problem field"
9: "action"
10."runs"
11."target"
12."John"
13."ta-status"
14."blue"
15."status-apply"
16."red"
17."lore"
18."lore ipsum dolor sit amet"

Please note problem field should be 1 result only

This question started when I tried to improve my answer to this SO question here: JS: deserializing a string with a JSON-like structure

I have done a classic for, but then user Redu created a regex based answer. Yet I didn't like because the field names had to be fixed. So I tried to create a regex with capturing groups that go back to check last comma, but I quickly discovered that my regex skills don't go that far (yet). So I thought in creating this question so we can learn with the regex masters out there.

3
  • That's the challenge. The key is the thing between last comma and : Commented May 17, 2016 at 14:58
  • Is the double space before action intended ? Commented May 17, 2016 at 15:03
  • no... edited. But the spaces don't matter. Commented May 17, 2016 at 15:05

1 Answer 1

1

This regex could help you:

([\w-]+): ([\w,\s']+)(?:,|$)

Demo

It capture every key/value separated with a :

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

1 Comment

Hopefully your problem field does not contain a :

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.