0

I have defined the delimiters as follows,

scanner.useDelimiter("a|b");

Then after executing next() method I want to know on which delimiter it did the split.

String s = scanner.next();
//char delim = scanner.nextDelimeter(); ??

Is there a way to achieve this in java while using Scanner class?

  • 2
    Use of Scanner is typical in code used for learning, but rare in production. It may be easier to use alternative methods such as String.split(). Then you can examine the original string to see what the delimiter character was. – k314159 Mar 12 '21 at 10:54
  • Possibly could use match() and look at the match result to work out where in the input .... – Mr R Mar 12 '21 at 11:15

1 Answers1

0

You can change your pattern to keep delimiters. See this post how-to-split-a-string-but-also-keep-the-delimiters If you keep your delimiters you just need to call Scanner.next

Example:

Scanner scanner = new Scanner("99axxbssbyyaxxa");
scanner.useDelimiter("((?<=(a|b))|(?=(a|b)))");
while(scanner.hasNext()){
    System.out.println(scanner.next());
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28