Question

I am trying to do as my question states, sooo I have the following code which would find the match.

String test = scan.next();
if (test.equals("$let"))
return 1;

However, I would prefer to use hasNext as to not consume a token; however, when i do the following it fails.
if (scan.hasNext("$let"))
return 1;

I realize the when giving has next a variable it expects a pattern, but I thought if i don't have any regex symbols it should work. I also thought $ was possibly some regex symbol so I tried /$ however, that did not work!

Thanks for the help!

Was it helpful?

Solution

You should use \\$ to escape the regex, but it's easier to just get the next() and save the result.

OTHER TIPS

In general, if you have some arbitrary string that you want to match literally with no meanings to any regex metacharacters, you can use java.util.Pattern.quote.

Scanner sc = new Scanner("$)}**");
System.out.println(sc.hasNext(Pattern.quote("$)}**"))); // prints "true"
System.out.println(sc.hasNext("\\Q$)}**\\E")); // prints "true"
System.out.println(sc.hasNext("$)}**")); // throws PatternSyntaxException

You can also use the \Q and \E quotation markers, but of course you need to ensure that the quoted string must not itself contain \E.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top