-3

I'm trying to get out all numbers (integers and floats) out of a given String. For example:

"1.24 + 112 - 436 * 1.22 / 4 % 55"

I want to get 1.24 and the rest out of the string so I can do the math. Like this:

[1.24,+,112,-,436,1.22,/,4,%,55]
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
SSM
  • 379
  • 5
  • 16
  • Ye you want reverse polish notation. Google for some parsers to do that. Also you got `Scanner` class that can help you in parsing as well as `Integer.parseInt()` and `Float.parseFloat()` – Antoniossss May 13 '17 at 00:59

1 Answers1

0

Here you have regular expression for

public static void main(String[] args) {
        Pattern pat=Pattern.compile("\\d+\\.\\d++|\\d+|[-+=\\\\*/%]");
        String str="1.24+112-436*1.22/4%55";        
        Matcher matcher = pat.matcher(str);
        while(matcher.find()){
            System.out.println(matcher.group(0));
        }
    }

Output:

1.24
+
112
-
436
*
1.22
/
4
%
55

To handle negative numbers as well you will use Pattern.compile("-?\\d+\\.\\d++|-?\\d+|[-+=\\\\*/%]"); But there is a catch because there is no way to distict between x-y and x - y so you will have to assume that if there is no operator between 2 operands, there should be additon + resultion in x+(-y) and tha will be equal in both cases

But all in all, parsing math equasions can be complicated and tricky so you better use existing solution (google it out)

Antoniossss
  • 31,590
  • 6
  • 57
  • 99