Reputation: 93
I am currently working on an import feature in a Java project and am receiving objects as a string. A structure similar to JSON is being used here. Objects are enclosed in curly braces and lists go in square brackets.
I now have an object which is a bit more complex because it consists of lists of objects which themselves carry lists of more (other) objects. I do know how to get the inner objects but I am having difficulties separating the outer ones. I feel I am overlooking something rather simple but all the braces and brackets don't make it any easier.
Here is an axample of how an import string could look (I left the inner objects combined for readability):
[
{
[
{[oid1,oid2],VAL,id1},{[oid2],VAL,id2},
{[oid2,oid3,oid4],VAL,id3}
]
},
{
[
{[oid5,oid6],VAL,id1},
{[oid7,oid8],VAL,id3}
]
}
]
So far, I have this regex {\[([^]{]+)],([A-Z_]+),([^}]+)}
which matches on all the inner objects and returns their three components as groups.
Like so:
Match 1: {[oid1,oid2],VAL,id1}
Group 1: oid1,oid2
Group 2: VAL
Group 3: id1
That is already fine, but just returns a list of all inner objects. Now I need to find a way to get a list of outer objects paired with a list of only those inner objects they contain. I should add that I do not need to do this in one step, necessarily. I tried splitting the initial string, but couldn't come up with a solution that wouldn't "cut" too much from it, which breaks parsing the resulting strings. Any help is much appreciated!
Upvotes: 0
Views: 317
Reputation: 854
Is this the division you are looking for, before you add your regex for your inner object?
Used regex:
"]\\s+},\\s+\\{\\s+\\["
Regex in context and testbench:
public static void main(String[] args) {
String input = "[\n"
+ " {\n"
+ " [\n"
+ " {[oid1,oid2],VAL,id1},{[oid2],VAL,id2},\n"
+ " {[oid2,oid3,oid4],VAL,id3}\n"
+ " ]\n"
+ " },\n"
+ " {\n"
+ " [\n"
+ " {[oid5,oid6],VAL,id1},\n"
+ " {[oid7,oid8],VAL,id3}\n"
+ " ]\n"
+ " }\n"
+ "]";
List<String> resultList = Arrays.asList(input.split("]\\s+},\\s+\\{\\s+\\["));
resultList.forEach(s -> System.out.printf("%s%n === %n", s));
}
Output:
[
{
[
{[oid1,oid2],VAL,id1},{[oid2],VAL,id2},
{[oid2,oid3,oid4],VAL,id3}
===
{[oid5,oid6],VAL,id1},
{[oid7,oid8],VAL,id3}
]
}
]
Upvotes: 1