正则表达式,可以捕获逗号分隔的 key=value,其中值也包含逗号

问题描述 投票:0回答:1

我有这个输入字符串

   String input = "a=value1,b=va,lu,e,2,c=value3,d=value4,with,commas,,,,";
我想将其转换为键值对,这样它应该具有如下所示的值

所需输出:

a -> value1
b -> va,lu,e,2
c -> value3
d -> value4 with -> commas,,,,,
`

我尝试了以下 2 个正则表达式

(\\w+)=(.*?)(?:,|$)
跳过第一个逗号后的值条目
(\\w+)=(.*?)(?:,(\\w+)=|$)
这里它跳过备用键值对

下面是运行程序代码片段

public static Map < String, String > parseStringToMap() {
    Map < String, String > resultMap = new HashMap < > ();
    String input = "a=val,ue1,b=va,lu,e,2,c=value3,d=value4,with,commas,,,,";
    Pattern pattern = Pattern.compile("(\\w+)=(.*?)(?:,(\\w+)=|$)");
    Matcher matcher = pattern.matcher(input);

    while (matcher.find()) {
        String key = matcher.group(1);
        String value = matcher.group(2);
        resultMap.put(key, value);
    }

    return resultMap;
}

java regex regex-group
1个回答
0
投票

使用这个正则表达式

(\w+)=(((?!,\w+=).)*)

然后将匹配流式传输到地图:

Pattern pattern = Pattern.compile("(\\w+)=(((?!,\\w+=).)*)");
Map<String, String> map = pattern.matcher(input).results()
        .collect(toMap(mr -> mr.group(1), mr -> mr.group(2)));
© www.soinside.com 2019 - 2024. All rights reserved.