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.
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 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.