如何在Java Scanner中使用分隔符? [英] How do I use a delimiter in Java Scanner?

查看:847
本文介绍了如何在Java Scanner中使用分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

重点是理解正则表达式( 正则表达式 Scanner :: useDelimiter 。查找 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中使用分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆