解析带有定界符的字符串并将其加载到映射中? [英] Parse a string with delimiters and load it in a map?
问题描述
我在String下面有一个key1=value1, key2=value2
格式,我需要将它作为key=value
加载到地图(Map<String, String>)
中,因此我需要对逗号,
进行拆分,然后将cossn
加载为键和0
其值.
I have below String which is in the format of key1=value1, key2=value2
which I need to load it in a map (Map<String, String>)
as key=value
so I need to split on comma ,
and then load cossn
as key and 0
its value.
String payload = "cossn=0, abc=hello/=world, Agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
HashMap<String, String> holder = new HashMap();
String[] keyVals = payload.split(", ");
for(String keyVal:keyVals) {
String[] parts = keyVal.split("=",2);
holder.put(parts[0], parts[1]);
}
我在这行holder.put(parts[0], parts[1]);
上获得java.lang.ArrayIndexOutOfBoundsException
,并且正在发生此字符串Agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
的bcoz,因为它的值KHTML, like Gecko
中有一个额外的逗号.
I am getting java.lang.ArrayIndexOutOfBoundsException
at this line holder.put(parts[0], parts[1]);
and it is happening bcoz of this String Agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
since it has an extra comma in the value KHTML, like Gecko
.
我该如何解决?通常,在将其加载到地图中之后,下面应该是我的键和值.
How can I fix this? In general below should be my keys and value after loading it in a map.
Key Value
cossn 0
abc hello/=world
Agent Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
推荐答案
正如您所说的,密钥仅包含字母数字,以下内容可能是拆分的一种很好的启发方法:
As you said your keys only contain alphanumerics, the following would probably be a good heuristic for splitting:
payload.split("\\s*,\\s*(?=[a-zA-Z0-9_]+\\s*=|$)");
其中可能会分割成空格的逗号,其后是字符串或字母数字键,可选的空格和等号的结尾.
Which will split on probably whitespace framed commas that are followed by the end of the string or an alphanumeric key, optional whitespace and an equals sign.
这篇关于解析带有定界符的字符串并将其加载到映射中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!