gpt4 book ai didi

java - 如何在 Java 中使用带有 Scanner.useDelimiter 的分隔符?

转载 作者:IT老高 更新时间:2023-10-28 20:37:30 27 4
gpt4 key购买 nike

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

重点是理解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

关于java - 如何在 Java 中使用带有 Scanner.useDelimiter 的分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28766377/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com