简体   繁体   中英

Split String based on {} open and curly braces java

I have a String like this

String str = {"name":"SachText_singleLineText","value":"text project field"},{"name":"SachSlistSingle_singleSelect","value":"s1"},{"name":"SachYesno_boolean","value":["1"]}

I need to split it based on curly braces like this

[0] = {"name":"SachText_singleLineText","value":"text project field"}
[1] = {"name":"SachSlistSingle_singleSelect","value":"s1"}
[2] = {"name":"SachYesno_boolean","value":["1"]}

Currently, this is what I am trying to do

String[] projectfieldsValueArray = str.split("\\{\\{,\\}\\}");

I tried with several combinations from net but still not able to split to my requirement. Need help on proper regex need to be used in this scenario.

you can try with Pattern Matcher.

    String key = "(\\{.*?\\})";
    String str = //your string.;
    Pattern pattern = Pattern.compile(key);
    Matcher matcher = pattern.matcher(str);
    if (matcher.find())
    {
        System.out.println(matcher.group(0));
    }

Using regex is going to be very hard to get it working. Consider this string:

{"name":"{SachText},{singleLineText}","value":"text project field"},{"name":"{SachSlist},{Single_singleSelect}","value":"s1"}

There are substrings of "},{" inside quotes, making them part of the name itself, so you don't want to split those.

Your strings look like elements of a JSON array. Therefore, put them between "[" and "]" and use a JSON parser, such as Jackson, GSon or Moshi, and it will parse them properly.

I am assuming ur string could be

String str = "{\"name\":\"SachText_singleLineText\",\"value\":\"text project field\"},{\"name\":\"SachSlistSingle_singleSelect\",\"value\":\"s1\"},{\"name\":\"SachYesno_boolean\",\"value\":[\"1\"]}";

If you need a String in between braces please use regex [{}] if you need a split string with braces you can prepend "{" and append "}"

 String[] arrOfStr = str.split("[{}]");
        for(String a: arrOfStr) {
            System.out.println(  a );
        }

O/p: "name":"SachText_singleLineText","value":"text project field", "name":"SachSlistSingle_singleSelect","value":"s1", "name":"SachYesno_boolean","value":["1"]

With str taken from Suvarn Banarjee and the hint from Mark Rotteveel:

String str = "{\"name\":\"SachText_singleLineText\",\"value\":\"text project field\"},{\"name\":\"SachSlistSingle_singleSelect\",\"value\":\"s1\"},{\"name\":\"SachYesno_boolean\",\"value\":[\"1\"]}";
String[] parts = str.split("(?<=\\}),(?=\\{)");

But again, this looks like JSON to me, so it's usually best to use a JSON library, since I'm pretty sure you're not done with just splitting.

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