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.
CodePudding user response:
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));
}
CodePudding user response:
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"]
CodePudding user response:
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.
CodePudding user response:
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.