Pattern is not splitting as desired, fails to spli

2019-03-03 05:41发布

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 +]

标签: java regex rpn
2条回答
SAY GOODBYE
2楼-- · 2019-03-03 05:53

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.

查看更多
萌系小妹纸
3楼-- · 2019-03-03 06:06

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*[-+*/$£])" );
查看更多
登录 后发表回答