zoukankan      html  css  js  c++  java
  • Java基础之一组有用的类——为标记定义自己的模式(ScanString)

    控制台程序。

    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 }
  • 相关阅读:
    eclipse上运行spark程序
    Java实现高斯模糊算法处理图像
    Hadoop环境共享
    P1182 数列分段`Section II`
    NOIP2015题解
    镜面上的迷失之链 —— 二分判定性问题
    网络最大流
    [IOI2008]Island
    历史的进程——单调队列
    快速幂
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3442374.html
Copyright © 2011-2022 走看看