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

NoM*_*ors 49 java delimiter

sc = new Scanner(new File(dataFile));
sc.useDelimiter(",|\r\n");
Run Code Online (Sandbox Code Playgroud)

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

Jor*_*lla 83

扫描仪还可以使用除空白之外的分隔符.

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(); 
Run Code Online (Sandbox Code Playgroud)

关键是理解regex里面的正则表达式()Scanner::useDelimiter.在这里查找useDelimiter教程.


这里开始使用正则表达式,您可以找到一个很好的教程.

笔记

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
Run Code Online (Sandbox Code Playgroud)

  • 你能解释一下吗?``\\ s*fish \\ s*"`谢谢. (3认同)

cнŝ*_*ŝdk 9

使用Scanner,默认分隔符是空白字符.

但是,Scanner可以根据一组分隔符定义令牌的开始结束位置,可以通过两种方式指定:

  1. 使用Scanner方法:useDelimiter(String pattern)
  2. 使用Scanner方法:useDelimiter(Pattern pattern)其中Pattern是指定分隔符集的正则表达式.

因此,useDelimiter()方法用于标记Scanner输入,并且行为类似于StringTokenizer类,请查看这些教程以获取更多信息:

这是一个例子:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}
Run Code Online (Sandbox Code Playgroud)

打印此输出:

Anna Mills
Female
18
Run Code Online (Sandbox Code Playgroud)