[英]Split a mathematical expression
I'm separating a string which is a mathematical expression, I want to split every number, operator and parentheses, and send them to an array, this is my code: 我正在分离一个字符串,这是一个数学表达式,我想拆分每个数字,运算符和括号,然后将它们发送到数组,这是我的代码:
Scanner in = new Scanner(System.in);
System.out.println("enter the expression :");
String infija = in.nextLine();
String separate[] = infix.split("(?=[-+*/%()])|(?<=[^-+*/%][-+*/])|(?<=[()])");
but when I enter an expression with m modulus, the code does not separate it. 但是当我输入一个模数为m的表达式时,代码不会将其分开。
For example, entering 例如,输入
(2/3)+(2%1)
the expected result is: 预期结果是:
[(,2, /, 3,), +,(, 2, %, 1,)]
There's an easier way: 有一种更简单的方法:
String separate[] = infix.split("\\b|(?<=\\D)(?=\\D)");
This splits on word boundary and between non-digits. 这在单词边界和非数字之间分裂。
In regex, a "word" char is any digit, letter or underscore. 在正则表达式中,“单词”字符是任何数字,字母或下划线。 A word boundary is between a word char and a non-word char (and visa versa).
单词边界位于单词char和非单词char之间(反之亦然)。
Test code: 测试代码:
System.out.println(Arrays.toString("2/(3+2)%1".split("\\b|(?<=\\D)(?=\\D)")));
output: 输出:
[2, /, (, 3, +, 2, ), %, 1]
This should do it, 应该这样做
String myString= "(2/3)+(2%1)";
String[] result = myString.split("(?<=[-+*/%()])|(?=[-+*/%()])");
System.out.println(Arrays.toString(result));
output: 输出:
[(, 2, /, 3, ), +, (, 2, %, 1, )]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.