Reputation: 6610
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.
Upvotes: 0
Views: 69
Reputation: 29451
This regex could help you:
([\w-]+): ([\w,\s']+)(?:,|$)
It capture every key/value separated with a :
Upvotes: 1