1

I have a string (1, 2, 3, 4), and I want to parse the integers into an array.

I can use split(",\\s") to split all but the beginning and ending elements. My question is how can I modify it so the beginning and ending parenthesis will be ignored?

1
  • 4
    Have you thought about looking at the substring from 1 to length-2? If you do this, then the string should be separable with split. Commented May 16, 2012 at 18:31

4 Answers 4

3

You'd be better served by matching the numbers instead of matching the space between them. Use

final Matcher m = Pattern.compile("\\d+").matcher("(1, 2, 3, 4)");
while (m.find()) System.out.println(Integer.parseInt(m.group()));
Sign up to request clarification or add additional context in comments.

1 Comment

The less reliable the data, the better this solution.
2

Use 2 regexes: first that removes parenthesis, second that splits:

Pattern p = Pattern.compile("\\((.*)\\)");
Matcher m = p.matcher(str);
if (m.find()) {
    String[] elements = m.group(1).split("\\s*,\\s*");
}

And pay attention on my modification of your split regex. It is much more flexible and safer.

Comments

1

You could use substring() and then split(",")

  String s = "(1,2,3,4)";
  String s1 = s.substring(1, s.length()-2);//index should be 1 to length-2
  System.out.println(s1);

  String[] ss = s1.split(",");
  for(String t : ss){
    System.out.println(t);
  }

Comments

0

Change it to use split("[^(),\\s]") instead.

1 Comment

This will create 2 extra elements: empty strings in the beginning and end.

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.