Scanner Without Separator

I would like to be able to parse strings like the following: "123456abcd9876az45678". BNF is as follows:

number: ? definition of an int ?
word: letter { , letter }
expression: number { , word , number }

However, the java.util.scanner class does not allow me to do the following:

Scanner s = new Scanner("-123456abcd9876az45678");
System.out.println(s.nextInt());
while (s.hasNext("[a-z]+")) {
    System.out.println(s.next("[a-z]+"));
    System.out.println(s.nextInt());
}

Ideally, this should give:

-123456
abcd
987
az
45678

I really hoped that java.util.Scanner would help me, but it looks like I will need to create my own scanner. Is there anything that is already present in the Java API to help me?


The question is missing too much information. And so all the answers are valid for the question, but not for my problem.

+3
source share
4 answers

, AFAIK. , , , findInLine() findWithinHorizon(). findWithinHorizion().

Scanner s = new Scanner("-123456abcd9876az45678");
Pattern num = Pattern.compile("[+-]?\\d+");
Pattern letters = Pattern.compile("[A-Za-z]+");
System.out.println(s.findWithinHorizon(num, 0));
String str;
while ((str = s.findWithinHorizon(letters, 0)) != null) {
    System.out.println(str);
    System.out.println(s.findWithinHorizon(num, 0));
}
+3
+1

, findWithinHorizon \G (= ).

( ):

Scanner scanner = new Scanner(input);
while (true) {
  String letters = scanner.findWithinHorizon("\\G\\s*\\[a-zA-Z]+", 0);
  if (letters != null) {
    System.out.println("letters: " + letters.trim());
  } else {
    String number = scanner.findWithinHorizon("\\G\\s[+-]?[0-9]+", 0);
    if (number != null) {
      System.out.println("number: " + number.trim());
    } else if (scanner.findWithinHorizon("\\G\\s*\\Z", 0) != null) {
      System.out.println("end");
      break;
    } else {
      System.out.println("unrecognized input");
      break;
    }
  }
}

, , .

+1

You can set a delimiter to a template that cannot match anything, for example.

Scanner s = ...
s.useDelimiter("(?!=a)a");
-1
source

Source: https://habr.com/ru/post/1787809/


All Articles