Reputation: 172
I tried to explain the pattern below. The key-value pair parsing should succeed if the values are separated by a new line or a comma. But separators should not create empty values, like a comma at the beginning, at the end or two consecutive commas, etc. So that I could get only key-value pairs by just calling capture groups.
key:value # should succeed
key:value,key:value,key:value # should succeed, can be called $1, $2, $3, etc.
key:value, # should fail
,key:value # should fail
key:value,key:value,key:value, # should fail
key:value,,key:value,key:value # should fail
I tried something like below, but it matches only first and last ones, excluding the others in one line.
^(key:value)(?:,(key:value))+$
Any ideas to capture the repeating pairs?
Edit: The "key" and "value" have their own patterns and I have solved them already. I am struggling with repeating capture groups. Just to clarify.
Upvotes: 0
Views: 169
Reputation: 329
Adding a simple OR-Block to your regex seems to do the job for your provided example:
^(key:value)(?:,(key:value))+$|^key:value$
Also, I can suggest regex101.com, It's by far the best tool to use for regex debugging!
Upvotes: 1