LandonSchropp
LandonSchropp

Reputation: 10274

Java Pattern New Line Problem

In reading the documentation for Pattern, it declares \s as a whitespace character: [ \t\n\x0B\f\r]. So why does the second scanner below return null, and how can I get the pattern to work with the new line character?

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {

        String pattern = "\\s*a";

        Scanner scanner1 = new Scanner("    \t a");
        Scanner scanner2 = new Scanner("  \t\n a");

        System.out.println(scanner1.findInLine(pattern));
        System.out.println(scanner2.findInLine(pattern));
    }
}

Output:

         a
null

Upvotes: 1

Views: 1130

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170308

findInLine stops when it encounters a line break (as the name suggests):

"  \t\n a"
 ^^^^
   |  
   +-- this is where findInLine(...) searches for the pattern: `\s*a`

You should use findWithinHorizon(...) instead:

String pattern = "\\s*a";
Scanner scanner1 = new Scanner("    \t a");
Scanner scanner2 = new Scanner("  \t\n a");
System.out.printf(">%s<\n\n", scanner1.findInLine(pattern));
System.out.printf(">%s<", scanner2.findWithinHorizon(pattern, 0));

will print:

>        a<

>   
 a<

Upvotes: 7

Related Questions