带有正则表达式定界符的Java扫描仪 [英] Java Scanner with regex delimiter
问题描述
为什么以下代码返回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屋!