need to change regex for additional postfix criteria [duplicate]

好久不见. 提交于 2019-12-02 18:09:58

问题


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:


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


来源:https://stackoverflow.com/questions/27602066/need-to-change-regex-for-additional-postfix-criteria

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