sixtyfootersdude
sixtyfootersdude

Reputation: 27231

Java: Pattern, Scanner example does not work

I am curious why this pattern doesn't work.

String same = "==== Instructions ====";
Pattern title4 = Pattern.compile(same);
Scanner scan = new Scanner(same);
System.out.println(scan.hasNext(same));

returns:

false

Upvotes: 2

Views: 1427

Answers (2)

MicSim
MicSim

Reputation: 26796

The default Scanner delimiter is whitespace. The hasNext(...) method takes care of the delimiter and thus it would split the string at whitespaces and first check against ====, as kuropengin said.

Nonetheless it seems that you have a typo in your code, as you don't use the defined pattern at all. Your code should probably read:

String same = "==== Instructions ====";
Pattern title4 = Pattern.compile(same);
Scanner scan = new Scanner(same);
System.out.println(scan.hasNext(title4));

But what you are looking for is the findInLine(...) method. It will ignore the delimiter when searching for matches. The following code

String same = "==== Instructions ====";
Pattern title4 = Pattern.compile(same);
Scanner scan = new Scanner(same);
System.out.println(scan.findInLine(title4));

will return:

==== Instructions ====

Upvotes: 5

wkl
wkl

Reputation: 79931

Java's java.util.Scanner breaks up its input based on some delimiter. By default, the delimiter pattern matches whitespace, so your input to the scanner does not remain intact in this case, and you would get "====", "Instructions", "====" from the Scanner.

Upvotes: 2

Related Questions