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

时间:2015-02-27 13:35:01

标签: java delimiter

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

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

3 个答案:

答案 0 :(得分:70)

  

扫描仪还可以使用空格以外的分隔符。

来自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教程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

答案 1 :(得分:8)

使用Scanner时,默认分隔符是空格字符。

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

  1. 使用扫描仪方法:useDelimiter(String pattern)
  2. 使用扫描程序方法:useDelimiter(Pattern pattern)其中Pattern是指定分隔符集的正则表达式。
  3. 所以useDelimiter()方法用于标记扫描器输入,行为类似于StringTokenizer class,请查看这些教程以获取更多信息:

    这是一个Example

    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();
    }
    

    打印此输出:

    Anna Mills
    Female
    18
    

答案 2 :(得分:3)

例如:

String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);

这将允许您使用Enter作为分隔符。

因此,如果您输入:

Hello world (ENTER)

它将打印'Hello World'。