Java基础之一组有用的类——为标记定义自己的模式(ScanString)

时间:2021-01-26 08:08:04

控制台程序。

Scanner类提供了一种方式,用来指定如何识别标记。这需要使用next()方法的两个重载版本。其中的一个版本接受Pattern类型的参数。另一个版本接受String类型的参数,用来指定标识标记的正则表达式。在这两个版本中,标记都返回为String类型。

 import java.util.Scanner;
import java.util.regex.Pattern; public class ScanString {
public static void main(String[] args) {
String str = "Smith , where Jones had had 'had', had had 'had had'.";
String regex = "had";
System.out.println("String is:\n" + str + "\nToken sought is: " + regex); Pattern had = Pattern.compile(regex);
Scanner strScan = new Scanner(str);
// strScan.useDelimiter("[^\\w*]");
int hadCount = 0;
while(strScan.hasNext()) {
if(strScan.hasNext(had)) {
++hadCount;
System.out.println("Token found!: " + strScan.next(had));
} else {
System.out.println("Token is : " + strScan.next());
}
}
System.out.println(hadCount + " instances of \"" + regex + "\" were found.");
}
}