Java: Pattern behaves differently in Scanner

Viewed 237

Came across a strange behavior of regex matching in Java. The first output command prints true as expected, but when the same string is packed into Scanner, the output is false. What am I doing wrong?

public static void main(String[] args) {
  Pattern p = Pattern.compile(" *\\[");
  System.out.println(p.asPredicate().test("[]")); //true

  Scanner s = new Scanner("[]");
  System.out.println(s.hasNext(" *\\[")); //false
}
2 Answers
Related