delimiter 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.

Easy example from 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();

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.

Notes

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值