Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner vs Matcher - Regular Expressions, Matcher works, Scanner doesn't

Why the 1st block works but the 2nd block doesn't?

int numberOfDigits = 2;
Pattern p = Pattern.compile("[01]{"+numberOfDigits+"}");
Matcher m = p.matcher("101100101011010011111000");
while(m.find()){
    System.out.println(m.group());
}

BLock 2

Scanner scannerSegment = new Scanner("101100101011010011111000");
   while(scannerSegment.hasNext(p)){
    String segment = scannerSegment.next(p);
        System.out.println(segment);

    }
like image 508
Achow Avatar asked Apr 17 '13 16:04

Achow


1 Answers

Scanner is not the appropriate utility to retrieve patterns using its hasNext(Pattern pattern) method . It will check if the next complete token has the requested pattern .

Java API is the best document.

Some excerpts:

hasNext() : Returns true if the next complete token matches the specified 
pattern. A complete token is prefixed and postfixed by input that matches 
the delimiter pattern.`

So if you change the input to be delimited by space or any other delimiter ( other delimiters have to be set after defining the Scanner object ) , it will work. So this should work(for the current pattern):

Scanner scannerSegment = new Scanner("10 11 00 10 10 11 01 00 11 11 10 00");

Even this will work(for the current pattern):

Scanner scannerSegment = new Scanner("10,11,00,10,10,11,01,00,11,11,10,00");
scannerSegment.useDelimiter(",");

EDIT: Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

like image 182
AllTooSir Avatar answered Nov 10 '22 17:11

AllTooSir