简单数学方程的正则表达式 [英] regex for simple math equation
本文介绍了简单数学方程的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想识别整数或小数以及四个简单的操作,分解为标记我无法让小数生效,你能帮忙吗?
I want to recognize integers or decimals and the four simple operations, broken into tokens I can't get the decimal to work, can you please help?
我的注册号是
expression = "2.7 + 3 * (1 + 2)";
String expRegString = "\\d+(\\.\\d+)*|[\\(\\)\\+\\-\\*\\/]";
Pattern expPattern = Pattern.compile(expRegString);
Matcher expMatcher = expPattern.matcher(expression);
while (expMatcher.find()){
System.out.println(expMatcher.group());
}
给我 "+", "3", "(" , "1", "+" , "2",")"
正确的结果是 "2.7","+", "3", "(" , "1", "+" , "2",")"
>
推荐答案
您可以尝试删除所有空格,然后在字符 -
+<之前或之后的每个位置拆分数据/code>
*
/
(
)
.
You can try removing all spaces and then split your data on every place that is before or after characters -
+
*
/
(
)
.
这应该可以解决问题
String expression = "2.7 + 3 * (1 + 2)";
String[] tokens = expression.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String token : tokens)
System.out.println(token);
输出
2.7
+
3
*
(
1
+
2
)
这篇关于简单数学方程的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文