RegEx to match elements in a string separated by comma ignoring comma inside double quotes, curly brackets and square brackets

huangapple go评论126阅读模式
英文:

RegEx to match elements in a string separated by comma ignoring comma inside double quotes, curly brackets and square brackets

问题

我有一个以下的string值:

String str = {"A":"不要分隔","B":"OPM","C":[1,2,"AB",{"1":{"1":2,"2":[1,2]},"2":2}],"D":{"1":1,"2":[{"1":1,"2":2,"3":3},9,10]}}; 

我该如何编写一个正则表达式来捕获其中由不在双引号、方括号或花括号内的逗号分隔的元素?我想通过类似以下的方式匹配并获取这些元素,使用模式匹配。

List<String> list = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    list.add(matcher.group());
}

元素应为:

"A":"不要分隔"
"B":"OPM"
"C":[1,2,"AB",{"1":{"1":2,"2":[1,2]},"2":2}]
"D":{"1":1,"2":[{"1":1,"2":2,"3":3},9,10]}

如果字符串如下所示:

String str = [1,2,{"A":1,"B":2},[19,10,11,{"A":1,"B":2}],100];

那么元素应为:

1
2
{"A":1,"B":2}
[19,10,11,{"A":1,"B":2}]
100
英文:

I have a string value as below

String str = {"A":"do not seperate,value","B":"OPM","C":[1,2,"AB",{"1":{"1":2,"2":[1,2]},"2":2}],"D":{"1":1,"2":[{"1":1,"2":2,"3":3},9,10]}};

How can I write a regular expression to capture its elements separated by a comma which is not inside double quotes, square brackets or curly brackets? I want to match and get the elements by doing something like below; using pattern matching.

List<String> list = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    list.add(matcher.group());
}

The elements should be,

"A":"do not seperate,value"
"B":"OPM"
"C":[1,2,"AB",{"1":{"1":2,"2":[1,2]},"2":2}]
"D":{"1":1,"2":[{"1":1,"2":2,"3":3},9,10]}

If the string is something like below

String str = [1,2,{"A":1,"B":2},[19,10,11,{"A":1,"B":2}],100]

Then the elements should be

1
2
{"A":1,"B":2}
[19,10,11,{"A":1,"B":2}]
100

答案1

得分: 1

由于这是一个 JSON 字符串您可以使用对象映射器解析它并将其作为键值对存储在哈希映射中

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.*;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) throws IOException {
        String str = "{\"A\":\"不要分开,数值\",\"B\":\"OPM\",\"C\":[1,2,\"AB\",{\"1\":{\"1\":2,\"2\":[1,2]},\"2\":2}],\"D\":{\"1\":1,\"2\":[{\"1\":1,\"2\":2,\"3\":3},9,10]}}";
        JSONObject obj = new JSONObject(str);
        HashMap<String, Object> result = new ObjectMapper().readValue(str, new TypeReference<Map<String, Object>>() {
        });
        result.entrySet().stream().forEach(System.out::println);
    }
}

**输出**

A=不要分开数值
B=OPM
C=[1, 2, AB, {1={1=2, 2=[1, 2]}, 2=2}]
D={1=1, 2=[{1=1, 2=2, 3=3}, 9, 10]}
英文:

Since its a json string you can parse it with object mapper and get them as key value pair in a hashmap.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.*;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) throws IOException {
        String str = &quot;{\&quot;A\&quot;:\&quot;do not seperate,value\&quot;,\&quot;B\&quot;:\&quot;OPM\&quot;,\&quot;C\&quot;:[1,2,\&quot;AB\&quot;,{\&quot;1\&quot;:{\&quot;1\&quot;:2,\&quot;2\&quot;:[1,2]},\&quot;2\&quot;:2}],\&quot;D\&quot;:{\&quot;1\&quot;:1,\&quot;2\&quot;:[{\&quot;1\&quot;:1,\&quot;2\&quot;:2,\&quot;3\&quot;:3},9,10]}}&quot;;
        JSONObject obj = new JSONObject(str);
        HashMap&lt;String, Object&gt; result = new ObjectMapper().readValue(str, new TypeReference&lt;Map&lt;String, Object&gt;&gt;() {
        });
        result.entrySet().stream().forEach(System.out::println);
    }
}

output

A=do not seperate,value
B=OPM
C=[1, 2, AB, {1={1=2, 2=[1, 2]}, 2=2}]
D={1=1, 2=[{1=1, 2=2, 3=3}, 9, 10]}

答案2

得分: 1

public static List<String> getStringElements(String str) {
    List<String> elementsList = new ArrayList<>();
    StringBuilder element = new StringBuilder();
    int bracketsCount = 0;
    int quotesCount = 0;
    char[] strChars = str.substring(1, str.length() - 1).toCharArray();
    for (char strChar : strChars) {
        element.append(strChar);
        if (strChar == '\"') {
            quotesCount++;
        } else if (strChar == '[' && quotesCount % 2 == 0) {
            bracketsCount++;
        } else if (strChar == '{' && quotesCount % 2 == 0) {
            bracketsCount++;
        } else if (strChar == '(' && quotesCount % 2 == 0) {
            bracketsCount++;
        } else if (strChar == ']' && quotesCount % 2 == 0) {
            bracketsCount--;
        } else if (strChar == '}' && quotesCount % 2 == 0) {
            bracketsCount--;
        } else if (strChar == ')' && quotesCount % 2 == 0) {
            bracketsCount--;
        } else if (strChar == ',' && bracketsCount == 0 && quotesCount % 2 == 0) {
            elementsList.add(element.substring(0, element.length() - 1));
            element = new StringBuilder();
        }
    }
    if (element.length() > 0) {
        elementsList.add(element.toString());
    }
    return elementsList;
}
英文:

You probably can do something like this

public static List&lt;String&gt; getStringElements(String str) {
List&lt;String&gt; elementsList = new ArrayList&lt;&gt;();
StringBuilder element = new StringBuilder();
int bracketsCount = 0;
int quotesCount = 0;
char[] strChars = str.substring(1, str.length() - 1).toCharArray();
for (char strChar : strChars) {
element.append(strChar);
if (strChar == &#39;\&quot;&#39;) {
quotesCount++;
} else if (strChar == &#39;[&#39; &amp;&amp; quotesCount % 2 == 0) {
bracketsCount++;
} else if (strChar == &#39;{&#39; &amp;&amp; quotesCount % 2 == 0) {
bracketsCount++;
} else if (strChar == &#39;(&#39; &amp;&amp; quotesCount % 2 == 0) {
bracketsCount++;
} else if (strChar == &#39;]&#39; &amp;&amp; quotesCount % 2 == 0) {
bracketsCount--;
} else if (strChar == &#39;}&#39; &amp;&amp; quotesCount % 2 == 0) {
bracketsCount--;
} else if (strChar == &#39;)&#39; &amp;&amp; quotesCount % 2 == 0) {
bracketsCount--;
} else if (strChar == &#39;,&#39; &amp;&amp; bracketsCount == 0 &amp;&amp; quotesCount % 2 == 0) {
elementsList.add(element.substring(0, element.length() - 1));
element = new StringBuilder();
}
}
if (element.length() &gt; 0) {
elementsList.add(element.toString());
}
return elementsList;
}

huangapple
  • 本文由 发表于 2020年10月18日 17:01:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64411489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定