gpt4 book ai didi

java - 在 Java 中使用分隔符逗号在嵌套大括号中拆分字符串

转载 作者:行者123 更新时间:2023-11-30 09:59:34 31 4
gpt4 key购买 nike

尝试在字符串中使用逗号作为分隔符进行拆分并添加到字符串数组中,但在使用正则表达式拆分字符串时遇到问题。

String[] stringParts = str1.split(",(?![^\\[]*\\])");

for (int i=0; i<stringParts.length; i++){
stringParts[i] = stringParts[i].trim();//remove trailing leading spaces.
}
//System out
for (String s:stringParts){
System.out.println(s);
}

输入字符串

String str="1, two, {\"\"Customization\"\":{\"\"EMPLOYEEID\"\":\"\"EMPID001\"\",\"\"MANAGER_ID\"\":\"\"MNGID001\"\",\"\"DEPARTMENT\"\":\"\"IT\"\"},\"\"OTHERDETAILS\"\":{\"\"GENDER\"\":\"\"M\"\",\"\"DESIGNATION\"\":\"\"SENIOR\"\",\"\"TEAM\"\":\"\"QA\"\"}}, 8, nine,{{\"COMPANYNAME\":\"XYZ Ind Pvt Ltd\"},{[ten,{\"11\":\"12\"},{\"thirteen\":14}]}},\"fifteen\",16";

要求的输出

1
two
{""Customization"":{""EMPLOYEEID"":""EMPID001"",""MANAGER_ID"":""MNGID001"",""DEPARTMENT"":""IT""},""OTHERDETAILS"":{""GENDER"":""M"",""DESIGNATION"":""SENIOR"",""TEAM"":""QA""}}
8
nine
{{"COMPANYNAME":"XYZ Ind Pvt Ltd"},{[ten,{"11":"12"},{"thirteen":14}]}}
fifteen
16

最佳答案

这不是正则表达式设计的目的。您需要创建一个解析器。

或者你可以做类似的事情:

public static void main(String[] args) {
String str = "1, two, {\"\"Customization\"\":{\"\"EMPLOYEEID\"\":\"\"EMPID001\"\",\"\"MANAGER_ID\"\":\"\"MNGID001\"\",\"\"DEPARTMENT\"\":\"\"IT\"\"},\"\"OTHERDETAILS\"\":{\"\"GENDER\"\":\"\"M\"\",\"\"DESIGNATION\"\":\"\"SENIOR\"\",\"\"TEAM\"\":\"\"QA\"\"}}, 8, nine,{{\"COMPANYNAME\":\"XYZ Ind Pvt Ltd\"},{[ten,{\"11\":\"12\"},{\"thirteen\":14}]}},\"fifteen\",16";
StringTokenizer st = new StringTokenizer(str, ",", true);
int bracketCount = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
long brackets = token.chars().map(ch -> (ch == '{' ? 1 : (ch == '}' ? -1 : 0))).sum();
bracketCount += brackets;
if (bracketCount == 0 && ",".equals(token)) {
System.out.println("");
} else {
System.out.print(token);
}
}
}
  • 获取字符串并在 , 上拆分,保留分隔符作为输出标记
  • 计算打开和关闭的次数 { }。确保所有括号都已关闭。
  • 如果所有的 { } 都已经关闭,那么移到下一行

关于java - 在 Java 中使用分隔符逗号在嵌套大括号中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761426/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com