您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将key = value的字符串解析为Map

将key = value的字符串解析为Map

您可以使用

(\w+)=(.*?)(?=,\w+=|$)

请参阅regex演示

Java代码

public static Map<String, String> getAttributes(String attributes) {
    Map<String, String> attr = new HashMap<>();
    Matcher m = Pattern.compile("(\\w+)=(.*?)(?=,\\w+=|$)").matcher(attributes);
    while (m.find()) {
        attr.put(m.group(1), m.group(2));
    }
    return attr;
}

Java测试

String s = "Overtime=true,TransportCosts=1= 1,two, three,Billable=7200";
Map<String,String> map = getAttributes(s);
for (Map.Entry entry : map.entrySet()) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

结果:

Overtime=true
Billable=7200
TransportCosts=1= 1,two, three
其他 2022/1/1 18:16:23 有455人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶