如何在Java Scanner中使用分隔符? - 代码日志

如何在Java Scanner中使用分隔符?

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

我不明白分隔符是如何工作的,有人可以用外行来解释这个问题吗?

The scanner can also use delimiters other than whitespace.

简单的例子从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(); 

关键是要了解Scanner::useDelimiter的正则表达式(regex)。查找useDelimiter教程here

从正则表达式开始here you can find一个很好的教程。

笔记

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
http://stackoverflow.com/questions/28766377/how-do-i-use-a-delimiter-in-java-scanner

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何在Java Scanner中使用分隔符?