sc = new Scanner(new File(dataFile)); sc.useDelimiter(",|\r\n");
我不了解分隔符的工作原理,有人可以用外行人的方式解释吗?
扫描仪还可以使用空格以外的定界符。
来自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教程。
(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