For example, if the expression can have + - / * as operators, and floating point numbers
and the input is "3.5+6.5-4.3*4/5"
How should write a program that returns "3.5" "+" "6.5" "-" "4.3" "*" "4" "/" "5" one by one, I tried to write regular expression for these i.e. "[*]", "[/]","[+]","[-]" and pattern for number, and use:
Scanner sc = new Scanner("3.5+6.5-4.3*4/5");
and use sc.hasNext(pattern);
to loop through each pattern, I expect it to keep matching the start of the string until it match the number pattern, and sc.nect(pattern)
to get "3.5", and then "+" and so on.
But It seems like scanner does not work like this, and after looking through some other classes, I could not find a good solution.
You can create two capture groups with the following expression:
Regex
([0-9\.]+)|([+*\/\-])
Brief explanation
This alternates between:
[0-9\.]+
which matches the floating point numbersand
[+*\/\-]
which matches the mathematical symbols.Example Java code