Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to split key=value

I have a string like this:

KEY1=Value1, KE_Y2=[V@LUE2A, Value2B], Key3=, KEY4=V-AL.UE4, KEY5={Value5}

I need to split it to get a Map with key-value pairs. Values in [] should be passed as a single value (KE_Y2 is a key and [V@LUE2A, Value2B] is a value).

What regular expression should I use to split it correctly?

like image 250
Mad Max Avatar asked Dec 26 '22 05:12

Mad Max


1 Answers

There's a magic regex for the first split:

String[] pairs = input.split(", *(?![^\\[\\]]*\\])");

Then split each of the key/values with simply "=":

for (String pair : pairs) {
    String[] parts = pair.split("=");
    String key = parts[0];
    String value = parts[1];
}

Putting it all together:

Map<String, String> map = new HashMap<String, String>();
for (String pair : input.split(", *(?![^\\[\\]]*\\])")) {
    String[] parts = pair.split("=");
    map.put(parts[0], parts[1]);
}

Voila!


Explanation of magic regex:

The regex says "a comma followed by any number of spaces (so key names don't have leading blanks), but only if the next bracket encountered is not a close bracket"

like image 179
Bohemian Avatar answered Jan 12 '23 20:01

Bohemian