0

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 * 
+
tripleee
  • 175,061
  • 34
  • 275
  • 318
user1383163
  • 577
  • 1
  • 7
  • 24

1 Answers1

0

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 *
+
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274