1

I want to split a Java string:

"[1,2,3,4,5]"

So I have an array that only has the integers

1
2
3
4
5

Without the ", [ ]"

I tried

String[] test = x.split("(, )|(\\[\\)|(\\]\\)");

Which I found in another thread but it does not work properly. It keeps an empty string in test[0].

4
  • What does 'without the ",[ ]"' mean? I thought you wanted an array. Commented Apr 21, 2016 at 14:45
  • 1
    Why not try to replace the [] first, then split? Commented Apr 21, 2016 at 14:45
  • without replacing :- regex101.com/r/nW2lD2/1 Commented Apr 21, 2016 at 14:53
  • Yes i want an array but what i get back was "[1 2 3 4 5] Commented Apr 21, 2016 at 15:37

1 Answer 1

5

The easiest approach in this case seems that it would be to just replace the square brace characters [ and ] (via a replace() or replaceAll() call) and then perform your split() function using :

// Replace the square braces and then split using a comma
String[] output = input.replace("[", "").replace("]", "").split(",");

or :

// Replace the square braces and then split using a comma
String[] output = input.replaceAll("\\[|\\]", "").split(",");
Sign up to request clarification or add additional context in comments.

4 Comments

You can also parse it as a JSON Array. Bit of an overkill to add a JSON parser to the classpath just for this, but if you already have one, might as well use it.
@Wiktor and @Andreas, Both solid options, I went with the replace() / split() approach as it seemed the easiest to read for OP's purposes and for questions aimed at those just getting started (which I think this qualifies), I think readability is key.
In term of performance, the first option is clearly the best as you don't use any regex this way

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.