java 在地图中解析具有键=值对的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37401889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse a string with key=value pair in a map?
提问by user1950349
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.
我有下面的字符串,它的格式是key1=value1, key2=value2
我需要将它加载到地图中(Map<String, String>)
,key=value
所以我需要用逗号分割,
,然后cossn
作为键和0
它的值加载。
String payload = "cossn=0, itwrqm=200006033213";
Map<String, String> holder =
Splitter.on(",").trimResults().withKeyValueSeparator("=").split(payload);
I am using Splitter here to do the job for me but for some cases it is failing. For some of my strings, value has some string with equal sign. So for below string it was failing for me:
我在这里使用 Splitter 为我完成这项工作,但在某些情况下它失败了。对于我的一些字符串, value 有一些带等号的字符串。所以对于下面的字符串,它对我来说失败了:
String payload = "cossn=0, abc=hello/=world";
How can I make it work for above case? For above case key
will be abc
and value should be hello/=world
. Is this possible to do?
我怎样才能使它适用于上述情况?对于上述情况key
将是abc
,价值应该是hello/=world
。这有可能吗?
回答by Daniel Pryden
You can do this same thing with the Splitter
API directly:
你可以Splitter
直接用API做同样的事情:
Map<String, String> result = Splitter.on(',')
.trimResults()
.withKeyValueSeparator(
Splitter.on('=')
.limit(2)
.trimResults())
.split(input);
回答by Tomer Shemesh
you can add a number to say how many splits you want just add a 2 to split
您可以添加一个数字来说明您想要拆分的数量,只需添加 2 即可拆分
import java.util.HashMap;
public class HelloWorld{
public static void main(String []args){
HashMap<String, String> holder = new HashMap();
String payload = "cossn=0, abc=hello/=world";
String[] keyVals = payload.split(", ");
for(String keyVal:keyVals)
{
String[] parts = keyVal.split("=",2);
holder.put(parts[0],parts[1]);
}
}
}