Reputation: 10274
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
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