Reputation: 2169
I am trying to parse an input string like this
String input = "((1,2,3),(3,4,5),(2,3,4),...)"
with the aim of getting an array of String where each element is an inner set of integers i.e.
array[0] = (1,2,3)
array[1] = (3,4,5)
etc.
To this end I am first of all getting the inner sequence with this regex:
String inner = input.replaceAll("\\((.*)\\)","$1");
and it works. Now I'd like to get the sets and I am trying this
String sets = inner.replaceAll("((\\((.*)\\),?)+","$1")
But I can't get the result I expected. What am I doing wrong?
Upvotes: 1
Views: 2188
Reputation: 213391
Don't use replaceAll
to remove the parentheses at the ends. Rather use String#substring()
. And then to get the individual elements, again rather than using replaceAll
, you should use String#split()
.
String input = "((1,2,3),(3,4,5),(2,3,4))";
input = input.substring(1, input.length() - 1);
// split on commas followed by "(" and preceded by ")"
String[] array = input.split("(?<=\\)),(?=\\()");
System.out.println(Arrays.toString(array));
Upvotes: 3