在Java中使用Scanner,当字符串不是正则表达式模式时,如何使用hasNext(aString)?

发布于 2024-08-05 22:48:30 字数 336 浏览 1 评论 0原文

我正在尝试按照我的问题所述进行操作,所以我有以下代码可以找到匹配项。

<代码> 字符串测试 = 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冬天旳寂寞 2024-08-12 22:48:30

您应该使用 \\$ 来转义正则表达式,但获取 next() 并保存结果更容易。

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

戴着白色围巾的女孩 2024-08-12 22:48:30

一般来说,如果您有一些想要按字面意思匹配任何正则表达式元字符的任意字符串,则可以使用 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

您还可以使用 \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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文