arrays - Java: Splitting string equation into numbers and operators



I am trying to split a string equation into two arrays: numbers and operators.

String expr = "3/20.0";

String[] numbers = expr.split("[+-/\\*]");
String[] operators = expr.split("[^+-/\\*]+");


But my code prints out: [3, 20, 0] [, /, .]

But I'm trying to get [3, 20.0] [, /]

I am not sure why the comma is in front of the operators array, but mainly I just want 20.0 to be one element in the numbers array and keep decimal points out of my operators array.

1 Answer: 

The comma's are just showing you the element partition.
This [, means the first element is blank.

Try these raw regex

For numbers, split on [^\d.]+
For operators, split on [\d.]+

And, I don't know if Java split can delete empty elements, but you'd want to
do a check post process if you can.

Split Notes -
[\d.]+ is a class that generally matches numbers, ie. 'dd.dd' ( leaves operators )
[^\d.]+ is the inverse where it matches operators ( leaves numbers )