3

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.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • 1
    I've always used `FileReader` and done it character by character. (Which you say you want to avoid.) I'll be interested to see if there's an easier way. – River Jul 14 '15 at 21:08
  • If you want to evaluate the expression later, and check it for correctness, you're probably better off with a context-sensitive parser rather than regular expressions. [`PEP`](http://www.coffeeblack.org/#projects-pep) is quite a simple Earley parser implementation for example. – biziclop Jul 14 '15 at 21:09
  • @Neil Kirk you can change the Scanner's delimiter from a space to whatever you want with the useDelimiter() method (although this doesn't help you in this scenario, wanted to point it out) – BoDidely Jul 14 '15 at 21:12
  • 1
    But more pertinent to your problem, `Scanner` parses tokens, and tokens are by default delimited by whitespace. You can change the delimiter by calling `useDelimiter()`, but I don't know how it'll behave if you set the delimiter to an empty string. It should be fine but I've never tried it. – biziclop Jul 14 '15 at 21:13
  • 1
    @biziclop That worked using empty delimiter! If you post as an answer I will accept it. – Neil Kirk Jul 14 '15 at 21:15
  • possible duplicate of [Can I convert a string to a math operation in java?](http://stackoverflow.com/questions/11577259/can-i-convert-a-string-to-a-math-operation-in-java) – Anirudh Ramanathan Jul 14 '15 at 21:24
  • @AnirudhRamanathan It is not an exact duplicate because I don't want to simply evaluate the expression, but parse it and manipulate it in other ways. – Neil Kirk Jul 14 '15 at 21:33

1 Answers1

1

Use a matcher instead of the scanner:

Matcher m = number_pattern.matcher(test2);
while(m.find()) {
    System.out.println(m.group(0));
}
fgb
  • 18,439
  • 2
  • 38
  • 52