2

我想识别整数或小数以及四个简单的操作,分成标记我无法让小数工作,你能帮忙吗?

我的注册是

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",")"

4

2 回答 2

3

您可以尝试删除所有空格,然后在字符之前或之后的每个位置拆分数据- + * / ( )

这应该可以解决问题

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
)
于 2013-11-10T15:43:51.183 回答
0

它可能对您有用:

expression = "2.7 + 3 * (1 + 2)";
String expRegString = "\\d+(\\.\\d+)*|\\(\\d+(\\.\\d+)*[\\+\\-\\*\\/]\\d+(\\.\\d+)*\\)";
于 2013-11-10T15:44:35.713 回答