Pattern is not splitting as desired, fails to split by +

谁都会走 提交于 2019-12-02 12:54:43

问题


I have the following code :

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.

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 +

would equal

[2 2 +, /, 3 +]

回答1:


You can use this regex:

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

RegEx Demo

In Java it would be:

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



回答2:


Maybe I am missing something, but from what you describe, I don't see why it needs to be so complicated. "[\\d. ]+?[-+/*£$]" seems to do exactly what you want.



来源:https://stackoverflow.com/questions/27604625/pattern-is-not-splitting-as-desired-fails-to-split-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!