繁体   English   中英

Java String.split()正则表达式拆分数学表达式

[英]Java String.split() Regex to split mathematical expression

我有一个字符串:

"a + b - (2.5 * d / 2) < f > g >= h <= (i == j)"

目前,我已经:

String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];

但这不能处理括号。 并且它也将运算符和值分开,但是我想要单个正则表达式,它将像上面这样分割表达式:

[a, +, b, -, (, 2.5, *, d, /, 2, ), <, f, >, g, >=, h, <=, (, i, ==, j, )]

我认为这可能更容易表达为您尝试提取的令牌,而不是拆分正则表达式。

String input = "-9 + a + b - (2.5 * d / 2) < f > g >= h <= (i == j) && (foo || bar)";
Pattern pattern = Pattern.compile("-?[0-9.]+|[A-Za-z]+|[-+*/()]|==|<=|>=|&&|[|]{2}");
Matcher match = pattern.matcher(input);
List<String> actual = new ArrayList<String>();
while (match.find()) {
    actual.add(match.group());
}
System.out.println(actual);

这给您带来您想要的结果

[-9, +, a, +, b, -, (, 2.5, *, d, /, 2, ), f, g, >=, h, <=, (, i, ==, j, ), &&, (, foo, ||, bar, )]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM