用数学表达式进行Java拆分 [英] Java Splitting With Math Expression
问题描述
我正在尝试拆分数学表达式.
I am trying to split a Math Expression.
String number = "100+500";
String[] split = new String[3];
我想做
- split [0] ="100"
- split [1] ="+"
- split [2] ="500"
我尝试了这个,但是我不知道该怎么写.
I tried this but I don't know what to write for splitting.
split = number.split(????);
推荐答案
您想在数字和非数字之间进行拆分而不消耗任何输入...您需要环顾四周:
You want to split between digits and non-digits without consuming any input... you need look arounds:
String[] split = number.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
正则表达式的火车残骸到底是什么东西?
What the heck is that train wreck of a regex?
它表示此答案的首句:
-
(?< = \ d)
表示前一个字符是数字 -
(?= \ D)
表示下一个字符为非数字 -
(?< = \ d)(?= \ D)
在一起将在 个数字和一个非数字 之间匹配 -
regexA | regexB
表示匹配regexA 或 regexB,用作以上几点,但反之亦然,数字无数字 >
(?<=\d)
means the previous character is a digit(?=\D)
means the next character is a non-digit(?<=\d)(?=\D)
together will match between a digit and a non-digitregexA|regexB
means either regexA or regexB is matched, which is used as above points, but non-digit then digit for the visa-versa logic
重要的一点是,环顾环境是不消耗的,因此拆分过程不会在拆分过程中吞噬任何输入内容.
An important point is that look arounds are non-consuming, so the split doesn't gobble up any of the input during the split.
以下是一些测试代码:
String number = "100+500-123/456*789";
String[] split = number.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(Arrays.toString(split));
输出:
[100, +, 500, -, 123, /, 456, *, 789]
要使用可能带有小数点的数字,请使用以下正则表达式:
To work with numbers that may have a decimal point, use this regex:
"(?<=[\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[\\d.])"
实际上只是将.
添加到作为数字"的字符上.
which effectively just add .
to the characters that are a "number".
这篇关于用数学表达式进行Java拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!