I would like to resolve this problem.
,
comma : split terms"
double quote : String value (ignore special char)[]
array
For instance:
input : a=1,b="1,2,3",c=[d=1,e="1,2,3"]
expected output:
a=1
b="1,2,3"
c=[d=1,e="1,2,3"]
But I could not get above result.
I have written the code below:
String line = "a=1,b=\"1,2,3\",c=[d=1,e=\"1,11\"]";
String[] tokens = line.split(",(?=(([^\"]*\"){2})*[^\"]*$)");
for (String t : tokens)
System.out.println("> " + t);
and my output is:
a=1
b="1,2,3"
c=[d=1
e="1,11"]
What do I need to change to get the expected output? Should I stick to a regular expression or might another solution be more flexible and easier to maintain?
This regex does the trick:
It works by adding a look-ahead for matching pairs of square brackets after the comma - if you're inside a square-bracketed term, of course you won't have balanced brackets following.
Here's some test code:
Output:
I know the question is nearly a year old, but... this regex is much simpler:
|
matches[complete brackets]
|
matches\"strings like this\"
Splitting on Group 1 Captures
You can do it like this (see the output at the bottom of the online demo):
This is a two-step split: first, we replace the commas with something distinctive, such as
@@SplitHere@@
Pros and Cons
{inside , curlies}
, you just add anotherOR
branch to the left of the regex:{[^{}]*}
Reference
This technique has many applications. It is fully explained in these two links.