如何在 Java 中将分隔符与 Scanner.useDelimiter 一起使用? [英] How do I use a delimiter with Scanner.useDelimiter in Java?

查看:20
本文介绍了如何在 Java 中将分隔符与 Scanner.useDelimiter 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sc = new Scanner(new File(dataFile));
sc.useDelimiter(",|
");

我不明白分隔符是如何工作的,有人可以通俗地解释一下吗?

I don't understand how delimiter works, can someone explain this in layman terms?

推荐答案

扫描器还可以使用除空格以外的分隔符.

The scanner can also use delimiters other than whitespace.

来自扫描仪API的简单示例强>:

Easy example from Scanner API:

 String input = "1 fish 2 fish red fish blue fish";

 // \s* means 0 or more repetitions of any whitespace character 
 // fish is the pattern to find
 Scanner s = new Scanner(input).useDelimiter("\s*fish\s*");

 System.out.println(s.nextInt());   // prints: 1
 System.out.println(s.nextInt());   // prints: 2
 System.out.println(s.next());      // prints: red
 System.out.println(s.next());      // prints: blue

 // don't forget to close the scanner!!
 s.close(); 

重点是理解正则表达式(regex)Scanner::useDelimiter.查找 useDelimiter 教程 这里.

The point is to understand the regular expressions (regex) inside the Scanner::useDelimiter. Find an useDelimiter tutorial here.

从正则表达式开始在这里您可以找到一个不错的教程.

To start with regular expressions here you can find a nice tutorial.

abc…    Letters
123…    Digits
d      Any Digit
D      Any Non-digit character
.       Any Character
.      Period
[abc]   Only a, b, or c
[^abc]  Not a, b, nor c
[a-z]   Characters a to z
[0-9]   Numbers 0 to 9
w      Any Alphanumeric character
W      Any Non-alphanumeric character
{m}     m Repetitions
{m,n}   m to n Repetitions
*       Zero or more repetitions
+       One or more repetitions
?       Optional character
s      Any Whitespace
S      Any Non-whitespace character
^…$     Starts and ends
(…)     Capture Group
(a(bc)) Capture Sub-group
(.*)    Capture all
(ab|cd) Matches ab or cd

这篇关于如何在 Java 中将分隔符与 Scanner.useDelimiter 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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