RegEx用于匹配由逗号分隔的字符串中的元素,忽略双引号、大括号和方括号内的逗号



我有一个string值,如下

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]}};

如何编写正则表达式来捕获由逗号分隔的元素,该逗号不在双引号、方括号或大括号内?我想通过做下面这样的事情来匹配和获得元素;使用模式匹配。

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

元素应该是

"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]}

如果字符串低于

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

由于它是一个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":"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]}}";
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=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]}

您可能可以执行类似的操作

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;
}

最新更新