M.Stack M.Stack - 2 months ago 7
C# Question

Extracting key value pair with regex pattern

I am trying to get key value pairs from a string like this

TestKeyAAA: Hello World TestKeyBBB: 987654321 TestKeyCCC: A long sentence with a date time in it 2016-09-29T20:15:11 some more text TestKeyDDD: 123456789


And want to receive paires like this

TestKeyAAA = „Hello World“
TestKeyBBB = „987654321“
TestKeyCCC = „A long sentence with a date time in it 2016-09-29T20:15:11 some more text“
TestKeyDDD = „123456789“


The pattern I am using is this

(.+?):(.+?)(?=(?:[^\s]+:)|(?:$))


It works good, except for the value of key TestKeyCCC. The problem is the „:“ in the date.

The keys only contain
[A-Z],[a-z],. and /


I tried it with the following pattern

([A-Za-z\.]+?):(.+?)(?=(?:[^\s]+:)|(?:$))


But this didn't work to. What am I doing wrong?

Answer

I think you need to exclude digits as well as whitespaces when matching for ":"

([A-Za-z\.]+?):(.+?)(?=(?:[^\s0-9]+:)|(?:$))
Comments