Reputation: 2244
I know it is simple, but I do not know why it does not work.
I try to check if next String in scanner is matched by the pattern: String should begins with
" DESCRIPTION"
.
So, I try:
Scanner sc = new Scanner(" DESCRIPTION = 'Header for scroller'");
System.out.println("Has Next = " + sc.hasNext("\\s+DESCRIPTION.*"));
but it does not work, why? Simpler regex works fine:
Scanner sc = new Scanner(" DESCRIPTION = 'Заголовки таблиц скроллеров'");
System.out.println("Has Next = " + sc.hasNext(".*DESCRIPTION.*"));
Upvotes: 2
Views: 1410
Reputation: 1190
This doesn't work for you because Scanner uses whitespace as a default delimiter. Thus hasNext cannot find \s+DESCRIPTION and finds .*DESCRIPTION.* or just DESCRIPTION.*. If you would have changed your code to
Scanner sc = new Scanner(" DESCRIPTION = 'Header for scroller'");
sc.useDelimiter( "_" );
System.out.println("Has Next = " + sc.hasNext("\\s+DESCRIPTION.*"));
then you would have expected result.
Upvotes: 0
Reputation: 1336
Its because the default delimiter pattern for scanner is \p{javaWhitespace}+
Hence the next token becomes DESCRIPTION
rather than <space><space>DESCRIPTION
Upvotes: 0
Reputation: 129507
sc.hasNext(pattern)
returns true
if the next token matches pattern
.
The next token here is "DESCRIPTION"
.
"DESCRIPTION"
matches .*DESCRIPTION.*
"DESCRIPTION"
does not match \s+DESCRIPTION.*
(since there are no spaces before the token)You could try this:
Scanner sc = new Scanner(" DESCRIPTION = 'Header for scroller'");
System.out.println("Has Next = " + sc.hasNext("DESCRIPTION.*"));
Has Next = true
Upvotes: 2
Reputation: 972
Perhaps not what you're looking for, but
Scanner sc = new Scanner(" DESCRIPTION = 'Header for scroller'".trim());
System.out.println("Has Next = " + sc.hasNext("^DESCRIPTION.*"));
did the trick for me...
Upvotes: 0
Reputation: 37813
From JavaDoc of Scanner#hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string
So
sc.hasNext("\\s+DESCRIPTION.*")
returns false because the next token is DESCRIPTION
(without any whitespace) and
sc.hasNext(".*DESCRIPTION.*")
returns true because both of the .*
match 0 characters before and after DESCRIPTION
.
Upvotes: 1