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