1

I have a String:

    String str = "(25, 4) (1, -6)";

I want to get the individual numbers. For now, this is what I am doing:

    String[] strNew = str.replaceAll("\\s+","").split("-?\\D+");

But below is what i get:

25
4
1
6 

I can't seem to get the negative on the 6. I have search on here from answers but none of the regex I found worked. Any thoughts?

Kaleb Blue
  • 487
  • 1
  • 5
  • 20
  • You would be better off creating a regexp for a single number (`-?\d+`), then using [this answer](http://stackoverflow.com/a/6020436/240443) to extract them all. It's much cleaner and less hacky, even though Java complicates the process and makes it into a chore. – Amadan Jan 19 '15 at 01:10

1 Answers1

1

This should help you:

    String text = "(25, 4) (1, -6)";
    ArrayList<String> list = new ArrayList<String>();
    try {
        Pattern pattern = Pattern.compile("-?\\d+");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            list.add(matcher.group());
        }
        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
            System.out.println(iterator.next());
        }
    } catch (PatternSyntaxException ex) {
    }
Andie2302
  • 4,825
  • 4
  • 24
  • 43