我想识别整数或小数以及四个简单的运算,分解为标记 我无法计算小数,你能帮忙吗?
我的注册是
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",")"
最佳答案
您可以尝试删除所有空格,然后在字符 -
+
*
之前或之后的每个位置拆分数据/
(
)
.
这应该可以解决问题
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
)
关于java - 简单数学方程的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19891565/