简体   繁体   中英

Split a string in Java with nested braces using delimiter comma outside

Trying to split using comma as a delimiter in the string and add into a string array, but facing problem while spliting the string using regex.

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

Input String

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

Required Output

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

This isn't something that regex is designed for. You need to create a parser.

Or you could do something similar to this:

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);
        }
    }
}
  • Take the string and split on , , keeping the delimiter as an output token
  • count the number of open and close { } . Ensure all brackets have been closed.
  • If all { } have been closed then move onto the next line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM