我想识别整数或小数以及四个简单的操作,分为标记 我不能让小数点工作,你能帮忙吗?
我的注册
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",")"
答案 0 :(得分:2)
您可以尝试删除所有空格,然后在字符-
+
*
/
(
{{之前或之后的每个位置拆分数据1}}。
这应该可以解决问题
)
输出
String expression = "2.7 + 3 * (1 + 2)";
String[] tokens = expression.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String token : tokens)
System.out.println(token);
答案 1 :(得分:0)
它可能适合您:
expression = "2.7 + 3 * (1 + 2)";
String expRegString = "\\d+(\\.\\d+)*|\\(\\d+(\\.\\d+)*[\\+\\-\\*\\/]\\d+(\\.\\d+)*\\)";