need to change regex for additional postfix criter

2020-05-07 07:08发布

So i have this code:

Pattern pattern = Pattern.compile("\\d*(\\s\\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());
}

When i was working on just parsing integers the regex was of course fine however i now need it to take into account that there can be a . to represent a floating point.

Wondering if someone can help me with adding this in

expected output should be :

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

1条回答
虎瘦雄心在
2楼-- · 2020-05-07 07:56

This would produce the output you want. The part next to the Logical OR | operator will matches the [-+*/$£] symbols from the remaining sub-string.

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);
ArrayList<String> output = new ArrayList<String>();
while (matcher.find()) {
    output.add(matcher.group());
}
for (String s: output)
{
    System.out.println(s);
}

Output:

4.0 5.0 2.0 /
+
7.0 -
11.0 34.0 2.0 /
3.0 /
1.0 *
+
查看更多
登录 后发表回答