I am working with a calculator , after writing up the whole statement in the EditText, I want to extract the numbers and calculator symbols from the edit text field. The numbers can be simple integers or decimal numbers, i.e; Float and Double. For example I have this string now, 2 + 2.7 - 10 x 20.000. The regex will extract the +,- and x separately and the numbers as; 2,2.7,10,20.000. Basically i need to regex for each.
-
Would you extract those and put in a String array or in a double/float array? Because if you convert those to numbers, `2.7` will keep as 2.7, but `20.000` will turn into 20, because the zeros in the right side of the dot have no value. Or better, is it `20000` or `20.000`? – Mateus Jul 29 '17 at 10:36
-
Yeah thats true and that doesnt matter if i write it as 20.0000 or 20, but the 2.7 do matter – Kode Gylaxy Jul 29 '17 at 10:57
1 Answers
The regex you're searching for will be different from the regex from the split. If you use a Pattern
for this, things will get really slow and complicated. So here we're using String#split()
.
Here is your regex:
"\s*([^\d.]+)\s*"
Regex Explanation:
\s*
- Matches every white space if available([^\d.]+)
- Capture everything but a digit and a dot together as many as possible\s*
- Matches every whitespace if available
Note[1]: Once again, as it's going to be used in the split, you don't want to capture the numbers, this regex will match anything but numbers and remove them from the string, so if you use them in a Pattern#exec()
you'll have a different output.
So this way we can simply:
"2 + 2.7 - 10 x 20.000".split("\\s*([^\\d.]+)\\s*");
Note[2]: The regex inside a String in Java must have its backslashes escaped like above's. And also, the capture groups (...)
are useless since we're just splitting it, feel free to remove them if you want.
JShell Output:
$1 ==> String[4] { "2", "2.7", "10", "20.000" }
Java snippet: https://ideone.com/CHjKNB

- 4,863
- 4
- 24
- 32
-
-
1You can do the same thing, just remove the `^` in the split. However, if an empty element appear in your array (Like: `{"", "+", "-"}`), you can remove them by doing [this](https://stackoverflow.com/a/5520808/7225971) – Mateus Jul 29 '17 at 11:12
-
1So, it would be something like this: `string.split("\\s*([\\d.]+)\\s*")` – Mateus Jul 29 '17 at 11:13