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?
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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With