用正则表达式分割一个简单的数学表达式 [英] Splitting a simple maths expression with regex

查看:456
本文介绍了用正则表达式分割一个简单的数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将正则表达式拆分为1.5 + 4.2 *(5 + 2)等运算符与运算符 - + * /所以输出将输入到数组中以便我可以单独解析

I am trying to have a regular expression split on equations like 1.5+4.2*(5+2) with operators - + * / so the output would be input into a array so I can parse individually

[0]1.5
[1]+
[2]4.2
[3]*
[4](
[5]5
[6]+
[7]2
[8]) 

我发现 \ b 将适用于 1 + 2 + 3 但是,如果我有小数点,它就不会分裂。

I have found out that the \b will work on 1+2+3 however if I were to have decimal points it would not split.

我尝试用 \ b(\.\d {1,2})拆分但是它不会在小数点上拆分

I have tried splitting with \b(\.\d{1,2}) however it does not split on the decimal point

推荐答案

Pattern pattern = Pattern.compile("((\\d*\\.\\d+)|(\\d+)|([\\+\\-\\*/\\(\\)]))");
Matcher m = pattern.matcher("1.5+4.2*(5+2)/10-4");
while(m.find()) {
    System.out.printf("%s ", m.group());
}

output: 1.5 + 4.2 * ( 5 + 2 ) / 10 - 4

您还可以使用?:来避免捕获组。我把它留下来简单。

You can also use ?: to avoid capturing groups. I left it to make it simple.

这篇关于用正则表达式分割一个简单的数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆