模式没有按需分割,无法用+分割 [英] Pattern is not splitting as desired, fails to split by +

查看:143
本文介绍了模式没有按需分割,无法用+分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(\\s\\d+(?:\\.\\d+)?)*\\s*[-\\+\\*/\\$£]");

String input = "4.0 5.0 2.0 / + 7.0 - 11.0 34.0 2.0 / 3.0 / 1.0 * +";
Matcher matcher = pattern.matcher(input);
List<String> output = new ArrayList<>();
while (matcher.find()) {
    output.add(matcher.group());
}

编译的模式经历了多次迭代,在当前迭代它将以下内容添加到列表中:

The pattern that is compiled has gone through a number of iterations, in it's current iteration it adds to the list the following :

[4.0 5.0 2.0 /, 7.0 -, 11.0 34.0 2.0 /, 3.0 /, 1.0 *]

它应该被所有操作拆分并将操作保留在拆分字符串中所以我会预期以下输出:

It should be splitting by all operations and keeping the operations in the split string so i would have expected the following output:

[4.0 5.0 2.0 /,+, 7.0 -, 11.0 34.0 2.0 /, 3.0 /, 1.0 *, +]

当它只找到一个运算符而不是一个运算符时,它看起来不会分裂数字。

It looks to be that is not splitting when it only finds an operator and not a number.

所以基本上我想要当前行为以及拆分运算符,这样如果它连续找到2个运算符,它就会将它们分开。如下:

So essentially i would like the current behaviour as well as it splitting operators such that if it finds 2 operators in a row it splits them up. such that the following:

2 2 + / 3 +

等于

[2 2 +, /, 3 +]


推荐答案

你可以使用这个正则表达式:

You can use this regex:

((?:\d+(?:\.\d+)?(?:\s+\d+(?:\.\d+)?)*)?\s*[-+*/$£])



RegEx演示



In它将是:

RegEx Demo

In Java it would be:

Pattern pattern = Pattern.compile
  ( "((?:\\d+(?:\\.\\d+)?(?:\\s+\\d+(?:\\.\\d+)?)*)?\\s*[-+*/$£])" );

这篇关于模式没有按需分割,无法用+分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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