控制台程序。
Scanner类提供了一种方式,用来指定如何识别标记。这需要使用next()方法的两个重载版本。其中的一个版本接受Pattern类型的参数。另一个版本接受String类型的参数,用来指定标识标记的正则表达式。在这两个版本中,标记都返回为String类型。
1 import java.util.Scanner; 2 import java.util.regex.Pattern; 3 4 public class ScanString { 5 public static void main(String[] args) { 6 String str = "Smith , where Jones had had 'had', had had 'had had'."; 7 String regex = "had"; 8 System.out.println("String is: " + str + " Token sought is: " + regex); 9 10 Pattern had = Pattern.compile(regex); 11 Scanner strScan = new Scanner(str); 12 // strScan.useDelimiter("[^\w*]"); 13 int hadCount = 0; 14 while(strScan.hasNext()) { 15 if(strScan.hasNext(had)) { 16 ++hadCount; 17 System.out.println("Token found!: " + strScan.next(had)); 18 } else { 19 System.out.println("Token is : " + strScan.next()); 20 } 21 } 22 System.out.println(hadCount + " instances of "" + regex + "" were found."); 23 } 24 }