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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:27:34  来源:igfitidea点击:

Parse a string with key=value pair in a map?

javastringsplitguavasplitter

提问by user1950349

I have below String which is in the format of key1=value1, key2=value2which I need to load it in a map (Map<String, String>)as key=valueso I need to split on comma ,and then load cossnas key and 0its 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 keywill be abcand 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 SplitterAPI 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]);
        }

     }
}