带有正则表达式定界符的Java扫描仪 [英] Java Scanner with regex delimiter

查看:73
本文介绍了带有正则表达式定界符的Java扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码返回false?

Why does the following code return false?

Scanner sc = new Scanner("-v ");
sc.useDelimiter("-[a-zA-Z]\\s+");
System.out.println(sc.hasNext());

奇怪的是-[a-zA-Z]//s+将返回true.

The weird thing is -[a-zA-Z]//s+ will return true.

我也不明白为什么它返回true:

I also can't understand why this returns true:

Scanner sc = new Scanner(" -v");
sc.useDelimiter("-[a-zA-Z]\\s+");
System.out.println(sc.hasNext());

推荐答案

扫描器用于将字符串分解为令牌.分隔符是标记之间的分隔符.分隔符是扫描程序不匹配所匹配的内容;他们被丢弃了.您是在告诉扫描程序-[a-zA-Z]\\s+是定界符,并且由于-v与该正则表达式匹配,因此它会跳过它.

A scanner is used to break up a string into tokens. Delimiters are the separators between tokens. The delimiters are what aren't matched by the scanner; they're discarded. You're telling the scanner that -[a-zA-Z]\\s+ is a delimiter and since -v matches that regex it skips it.

如果要查找与正则表达式匹配的字符串,请使用

If you're looking for a string that matches the regex, use String.matches().

如果您的目标确实是将字符串拆分为标记,那么您也可以考虑

If your goal really is to split a string into tokens then you might also consider String.split(), which is sometimes more convenient to use.

这篇关于带有正则表达式定界符的Java扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆