简单的数学表达式解析 [英] simple mathematical expression parsing
问题描述
我尝试编写equals
覆盖功能.我认为我写的没错,但问题是解析表达式.我有一个ArrayList<String>
的数组类型,它需要从键盘输入而不是评估结果.我可以与另一个ArrayList<String>
变量进行比较,但是如何将ArrayList<String>
与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,然后使用等于进行比较
如您所见,想要应用测试已经太久了.
我曾经分裂过,但它也分裂了组合数.例如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
推荐答案
在这里为您提供帮助的正则表达式是
The Regular Expression which helps you here is
"(?<=[-+*/()])|(?=[-+*/()])"
当然,您需要避免多余的空格.
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屋!