Reputation: 11
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("[^+-/\\*]+");
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(operators));
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.
Upvotes: 1
Views: 949
Reputation:
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 )
Upvotes: 1