Kom Tran Kom Tran - 1 month ago 8
Java Question

Scanner.hasNext based on beginning of next String

I am looking at the Scanner documentation (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) and I see that there are conditional hasNext methods that only return true if the next element satisfies a certain condition. Let's say I have the following scanner. How could I check whether the scanner's next term starts with an "a"?

Scanner s = new Scanner("asd ab anob");

Answer

The pattern that it's talking about is a regular expression.

The regular expression for "starts with an a" is "^a.*"

boolean a = s.hasNext("^a.*");
Comments