简体   繁体   English

Java:将字符串方程拆分为数字和运算符

[英]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("[^+-/\\*]+");

System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(operators));

But my code prints out: [3, 20, 0] [, /, .]但我的代码打印出来: [3, 20, 0] [, /, .]

But I'm trying to get [3, 20.0] [, /]但我想得到[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.我不确定为什么逗号在运算符数组的前面,但主要是我只想将 20.0 作为数字数组中的一个元素,并将小数点保留在我的运算符数组之外。

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.]+对于数字,在[^\\d.]+上拆分
For operators, split on [\\d.]+对于运算符,拆分[\\d.]+

And, I don't know if Java split can delete empty elements, but you'd want to而且,我不知道 Java split 是否可以删除空元素,但您想
do a check post process if you can.如果可以的话,做一个检查发布过程。


Split Notes -拆分笔记 -
[\\d.]+ is a class that generally matches numbers, ie. [\\d.]+是一个通常匹配数字的类,即。 'dd.dd' ( leaves operators ) 'dd.dd'(叶运算符
[^\\d.]+ is the inverse where it matches operators ( leaves numbers ) [^\\d.]+是与运算符匹配的反函数叶数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM