1

i have a string like String[] str = {"[5, 2, 3]","[2, 2, 3, 10, 6]"} and i need to take numbers to add into an integer list.

i tried to split first index into numbers to see if it will work, looks like:

String[] par = str[0].split("[, ?.@]+");

After the split i tried to see what array i get:

for(String a: par)
    System.out.println(a);

But when i wrote that code i get an array like this:

[5
2
3]

So, how can i get rid of this square brackets?

1
  • 2
    You know exactly which strings have which brackets, and you know exactly where they will be. What is preventing you from removing them? Commented Jun 10, 2021 at 23:53

1 Answer 1

1

Instead of your current pattern, I would use \\D+ which will split on one or more non-digits. Add a guard for the empty string too. Something like

String[] str = { "[5, 2, 3]", "[2, 2, 3, 10, 6]" };
for (String par : str) {
    for (String t : par.split("\\D+")) {
        if (t.isEmpty()) {
            continue;
        }
        System.out.println(Integer.parseInt(t));
    }
}

Outputs

5
2
3
2
2
3
10
6
Sign up to request clarification or add additional context in comments.

Comments

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.