0

I am planning to split a string which is composed of numbers and operators (eg. +,-,*,/) and store the numbers in an array and also store the operators in an array. I have managed to get the numbers and store them in an array with this code

String num = "58.5+98*78/96/78.7-3443*12-3";
String[] strings = (num.split("[+|*|/|-]"));
for (String string : strings) {
    System.out.println(string);
}

Which outputs:

  • 58.5
  • 98
  • 78
  • 96
  • 78.7
  • 3443
  • 12
  • 3

What I want to do/have is get the delimiters in the same order they appeared on the string, like this:

  • +
  • *
  • /
  • /
  • -
  • *
  • -

I know this has something to do with regex but I am having a hard time implementing it. Thank you for the help.

Ralph
  • 550
  • 3
  • 10
  • 25
  • if you also need the value of the captured match you need to use a proper regex class and not just `String.split`. – xander Nov 30 '17 at 09:40

1 Answers1

1

For something quick and dirty you can split using the negated regex and ignore/remove the empty strings.

String strings = (num.split("[^+|*|/|-]"));
for (String string : strings) {
    if (!string.equals("")) {
        System.out.println(string);
    }
}
Oleg
  • 6,124
  • 2
  • 23
  • 40