1

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?

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

@lowcoupling Those are look-behind and look-ahead respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.