简单的数学表达式解析 [英] simple mathematical expression parsing
问题描述
我尝试编写 equals
覆盖函数.我想我写得对,但问题在于解析表达式.我有一个 ArrayList
数组类型,它从键盘获取输入而不是评估结果.我可以与另一个 ArrayList
变量进行比较,但如何将 ArrayList
与 String
进行比较.例如,
I try to write equals
override function. I think I have written right but the problem is that parsing the expression. I have an array type of ArrayList<String>
it takes inputs from keyboard than evaluate the result. I could compare with another ArrayList<String>
variable but how can I compare the ArrayList<String>
to String
. For example,
String expr = "(5 + 3) * 12 / 3";
ArrayList<String> userInput = new ArrayList<>();
userInput.add("(");
userInput.add("5");
userInput.add(" ");
userInput.add("+");
userInput.add(" ");
userInput.add("3");
.
.
userInput.add("3");
userInput.add(")");
然后将 userInput 转换为 String 然后使用 equals 进行比较如您所见,申请测试时间太长了.我曾经拆分过,但它也拆分了组合数字.像 12
到 1
和 2
then convert userInput to String then compare using equals
As you see it is too long when a test is wanted to apply.
I have used to split but It splits combined numbers as well. like 12
to 1
and 2
public fooConstructor(String str)
{
// ArrayList<String> holdAllInputs; it is private member in class
holdAllInputs = new ArrayList<>();
String arr[] = str.split("");
for (String s : arr) {
holdAllInputs.add(s);
}
}
正如您所料,它没有给出正确的结果.如何修复?或者有人可以帮助编写正则表达式以根据需要正确解析它吗?作为输出,我得到:
As you expect it doesn't give the right result. How can it be fixed? Or can someone help to writing regular expression to parse it properly as wanted? As output I get:
(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3
而不是
(,5, ,+, ,3,), ,*, ,12, ,/, ,3
推荐答案
帮助您的正则表达式是
"(?<=[-+*/()])|(?=[-+*/()])"
当然,您需要避免不需要的空格.
and of course, you need to avoid unwanted spaces.
我们开始,
String expr = "(5 + 3) * 12 / 3";
.
. // Your inputs
.
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String s : arr)
{
System.out.println("Element : " + s);
}
请看我的实验:http://rextester.com/YOEQ4863
希望有帮助.
这篇关于简单的数学表达式解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!