[英]Java Scanner with regex delimiter
Why does the following code return false? 为什么以下代码返回false?
Scanner sc = new Scanner("-v ");
sc.useDelimiter("-[a-zA-Z]\\s+");
System.out.println(sc.hasNext());
The weird thing is -[a-zA-Z]//s+
will return true. 奇怪的是-[a-zA-Z]//s+
将返回true。
I also can't understand why this returns true: 我也无法理解为什么返回true:
Scanner sc = new Scanner(" -v");
sc.useDelimiter("-[a-zA-Z]\\s+");
System.out.println(sc.hasNext());
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. 您告诉扫描程序-[a-zA-Z]\\\\s+
是定界符,并且由于-v
与该正则表达式匹配,它会跳过它。
If you're looking for a string that matches the regex, use String.matches()
. 如果要查找与正则表达式匹配的字符串,请使用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. 如果您的目标确实是将字符串拆分为标记,则还可以考虑使用String.split()
,它有时更方便使用。
Thanks John Kugelman, I think you're right. 谢谢约翰·库格曼,我认为你是对的。
Scanner can use customized delimiter to split input into tokens. 扫描程序可以使用自定义的定界符将输入拆分为令牌。 The default delimiter is a whitespace. 默认的分隔符是空格。
When delimiter doesn't match any input, it'll result all the input as one token: 当分隔符不匹配任何输入时,它将所有输入作为一个标记生成:
Scanner sc = new Scanner("-v");
sc.useDelimiter( "-[a-zA-Z]\\s+");
if(sc.hasNext())
System. out.println(sc.next());
In the code above, the delimiter actually doesn't get any match, all the input "-v" will be the single token. 在上面的代码中,定界符实际上没有任何匹配,所有输入“ -v”将是单个标记。 hasNext() means has next token . hasNext()表示具有下一个标记 。
Scanner sc = new Scanner( "-v ");
sc.useDelimiter( "-[a-zA-Z]\\s+");
if(sc.hasNext())
System. out.println(sc.next());
this will match the delimiter, and the split ended up with 0 token, so the hasNext() is false. 这将与定界符匹配,并且拆分最终以0令牌结束,因此hasNext()为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.