use*_*349 1 java string split splitter guava
我下面有String,其格式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);
Run Code Online (Sandbox Code Playgroud)
我在这里使用Splitter为我完成这项工作,但在某些情况下失败了。对于我的某些字符串,value具有一些带等号的字符串。所以对于下面的字符串,它对我来说是失败的:
String payload = "cossn=0, abc=hello/=world";
Run Code Online (Sandbox Code Playgroud)
如何使它适用于上述情况?对于上述情况,key将为abc,值应为hello/=world。这可能吗?
您可以Splitter直接通过API 执行相同的操作:
Map<String, String> result = Splitter.on(',')
.trimResults()
.withKeyValueSeparator(
Splitter.on('=')
.limit(2)
.trimResults())
.split(input);
Run Code Online (Sandbox Code Playgroud)
您可以添加一个数字来说明您想要拆分的数量,只需添加 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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10379 次 |
| 最近记录: |