(\w+)=(.*?)(?=,\w+=|$)
详情
- (\w+) - 第 1 组:一个或多个单词字符
- = - 等号
- (.*?) - 第 2 组:除换行符以外的任何零个或多个字符,尽可能少
- (?=,\w+=|$) - 需要 , 的正面前瞻,然后是 1+ 个单词字符,然后是 =,或紧接在当前位置右侧的字符串结尾。
Java代码:
public static Map<String, String> getAttributes(String attributes) {
//去除空格' '、'{'、'}'、‘\n’等
attributes = attributes.replace(" ","").replace("\n","").replace("$","").replace("{", "").replace("}", "")
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 test :
String s = "{Overtime=true, \nTransportCosts=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