Parsing a mathematical expression without spaces
I am trying to use Scanner to parse a string for numbers and operators. It works for me if each token is separated by a space, but if there are no spaces the scanner doesn't seem to work. This example shows my problem:
final Pattern number_pattern = Pattern.compile("-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)");
String test1 = "5 + 6";
String test2 = "5+6";
Scanner sc1 = new Scanner(test1);
Scanner sc2 = new Scanner(test2);
boolean found1 = sc1.hasNext(number_pattern); // true
boolean found2 = sc2.hasNext(number_pattern); // false
I am looking for an easy way, preferably using something in the Java standard library to parse a string for numbers and operators. I try to avoid examining the string one character at a time.
A string can contain a long expression with many numbers and operators, and I need to extract all of them. So I couldn't replace all operators with a space, for example.
+3
source to share