我是正则表达式的初学者。
我在字符串下面:
失败:2,成功:1,获取:1
输出映射:获取包含以下所有键值的映射:
失败-2(键=失败,值= 2)
成功-1
获取-1
我尝试使用以下解决方案:
public static void main(String arg[]) {
String msg = "fail:1,success:1,policyfetch:1";
System.out.println(getKeyValuesFromMsg(msg));
}
public static Map getKeyValuesFromMsg(String msg) {
if (msg != null) {
Map keyvalues = new HashMap();
Pattern p = Pattern.compile("(\\w+):(,+)");
Matcher m = p.matcher(msg);
while (m.find()) {
keyvalues.put(m.group(1), m.group(2));
}
return keyvalues;
} else
return Collections.emptyMap();
}
答案 0 :(得分:2)
您可以使用split功能,以下代码段应该可以正常运行
Map<String,String> map = new HashMap();
String str = "fail:2,success:1,fetch:1";
String[] keyValueParts = str.split(",");
for(String s : keyValueParts){
String parts[] = s.split(":");
map.put(parts[0],parts[1]);
}
System.out.println(map);
答案 1 :(得分:0)
我本可以使用下面的方法。
public static void main(String arg[]) {
String msg = "fail:1,success:1,policyfetch:1";
System.out.println(getKeyValuesFromMsg(msg));
}
private static Map<Object, Object> getKeyValuesFromMsg(String msg) {
Map<Object,Object> mapObj = new HashMap<Object,Object>();
for (int i=0;i<msg.split(",").length;i++)
mapObj.put(msg.split(",")[i].split(":")[0],msg.split(",")[i].split(":")[1]);
return mapObj;
}
答案 2 :(得分:-1)
我的解决方案:
public static Map<String, Integer> trans2Map(String source) {
if (null == source) {
return Collections.emptyMap();
}
Map<String, Integer> result = new HashMap<>();
Arrays.stream(source.split(","))
.filter(pair -> pair.split(":").length == 2)
.forEach(pair -> {
String key = pair.split(":")[0];
Integer value;
try {
value = Integer.parseInt(pair.split(":")[1]);
} catch (Exception e) {
return;
}
result.put(key, value);
});
return result;
}