正则表达式以分割key = value [英] Regular expression to split key=value
问题描述
我有这样的字符串:
KEY1=Value1, KE_Y2=[V@LUE2A, Value2B], Key3=, KEY4=V-AL.UE4, KEY5={Value5}
我需要拆分它才能获得带键值对的Map。 []
中的值应作为单个值传递( KE_Y2
是一个键, [ V @ LUE2A,Value2B]
是一个值。)
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!
正则表达式是逗号后跟任意数量的空格(所以关键名称不要' t有前导空格),但只有遇到下一个括号不是一个近括号
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"
这篇关于正则表达式以分割key = value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!