I am trying to use Scanner to parse a string for numbers and operators. I've got it working if each token is separated by a space, but if there are no spaces 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 am trying to avoid examining the string one character at a time.
The string could 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.