Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract key-value pairs separated by space, with space in values

Assume a one-line string with multiple consecutive key-value pairs, separated by a space, but with space allowed also within values (not in keys), e.g.

key1=one two three key2=four key3=five six key4=seven eight nine ten

Correctly extracting the key-value pairs from above would produce the following mappings:

"key1", "one two"
"key2", "four"
"key3", "five six"
"key4", "seven eight nine ten"

where "keyX" can be any sequence of characters, excluding space.

Trying something simple, like

([^=]+=[^=]+)+

or similar variations is not adequate.

Is there a regex to fully handle such extraction, without any further string processing?

like image 222
PNS Avatar asked Nov 30 '22 18:11

PNS


2 Answers

\1 contains the key and \2 the value:

(key\d+)=(.*?)(?= key\d+|$)

Escape \ with \\ in Java:

(key\\d+)=(.*?)(?= key\\d+|$)

Demo: https://regex101.com/r/dO8kM2/1

like image 21
AMDcze Avatar answered Dec 05 '22 11:12

AMDcze


Try with a lookahead:

(\b\w+)=(.*?(?=\s\w+=|$))

As a Java String:

"(\\b\\w+)=(.*?(?=\\s\\w+=|$))"

Test at regex101.com; Test at regexplanet (click on "Java")

like image 94
Jonny 5 Avatar answered Dec 05 '22 12:12

Jonny 5