'Regex for key : value pair matching

I would like to accomplish some pattern matching in java with...

Regex pattern used

(?<key>[^:]+):(?<value>[^:]+)(?:,|$)

Text to parse:

a long key: with some long value, KeyA: ValueA, KeyB: ValueB, KeyC: ValueC, ValueD, ValueE, some text and https://www.example.orf, KeyF: 84,3 kg, KeyG: 34,3 x 234,3 x 54 cm

Desired result:

a long key: with some long value
KeyA: ValueA
KeyB: ValueB
KeyC: ValueC
ValueD
ValueE
some text and https://www.example.orf
KeyF: 84,3 kg
KeyG: 34,3 x 234,3 x 54 cm

the url breaks the whole thing unfortunately and i dont know how to extract those "keyless" values

thanks in advance,

fritz



Solution 1:[1]

I'm not sure my answer is correct, you probably have to ask Wiktor Stribi?ew who is the best I know, but I got this one:

https://regex101.com/r/dGBQ4s/1

The pattern: /[,\s]*(?<key>\b[^:,]+?): (?<value>.*?(?=$|,\s+\b[^:,]+: ))/g

I started off by thinking that the key was any char except : and , and that the \b for word boundary could help ignoring spaces between the items. This is why I added [,\s]* in front of it in order to "eat" them.

Then for the value, I used a non-greedy match with .*? to match anything but it had to be followed by the positive lookahead that could either match the end of the string or a next key definition.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick Janser