如何在Java中与Scanner.useDelimiter一起使用定界符? [英] How do I use a delimiter with Scanner.useDelimiter in Java?
本文介绍了如何在Java中与Scanner.useDelimiter一起使用定界符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
sc = new Scanner(new File(dataFile));
sc.useDelimiter(",|\r\n");
我不明白定界符是如何工作的,有人可以用外行的方式解释吗?
I don't understand how delimiter works, can someone explain this in layman terms?
推荐答案
扫描仪还可以使用除空格以外的定界符.
The scanner can also use delimiters other than whitespace.
来自 扫描器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
) ="https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.util.regex.Pattern)" rel ="noreferrer"> 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屋!
查看全文