在Java中使用Scanner,当字符串不是正则表达式模式时,如何使用hasNext(aString)?
我正在尝试按照我的问题所述进行操作,所以我有以下代码可以找到匹配项。
<代码> 字符串测试 = scan.next();
if (test.equals("$let"))
返回1;
但是,我更愿意使用 hasNext 因为不消耗令牌;但是,当我执行以下操作时,它会失败。
<代码> if (scan.hasNext("$let"))
返回1;
我意识到当给下一个变量时它需要一个模式,但我想如果我没有任何正则表达式符号它应该可以工作。我还认为 $ 可能是一些正则表达式符号,所以我尝试了 /$ 但是,这不起作用!
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 \\$ 来转义正则表达式,但获取 next() 并保存结果更容易。
You should use \\$ to escape the regex, but it's easier to just get the next() and save the result.
一般来说,如果您有一些想要按字面意思匹配任何正则表达式元字符的任意字符串,则可以使用
java.util.Pattern.quote
。您还可以使用
\Q
和\E
引号标记,但当然您需要确保带引号的字符串本身不能包含\E
。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
.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
.