zoukankan      html  css  js  c++  java
  • Java基础之一组有用的类——使用正则表达式搜索子字符串(TryRegex)

    控制台程序。

    正则表达式只是一个字符串,描述了在其他字符串中搜索匹配的模式。但这不是被动地进行字符序列匹配,正则表达式其实是一个微型程序,用于一种特殊的计算机——状态机。状态机并不是真正的机器,而是软件,专门用于解释正则表达式,根据正则表达式隐含的操作分析给定的字符串。

    Java中的正则表达式功能通过java.util.regex包中的两个类实现:Pattern类定义了封装正则表达式的对象;Matcher类定义了封装状态机的对象,可以使用给定的Pattern对象搜索特定的字符串。

     1 import java.util.regex.Matcher;
     2 import java.util.regex.Pattern;
     3 import java.util.Arrays;
     4 
     5 class TryRegex {
     6   public static void main(String args[]) {
     7     //  A regex and a string in which to search are specified
     8     String regEx = "had";
     9     String str = "Smith, where Jones had had 'had' had had 'had had's";
    10 
    11     // The matches in the output will be marked (fixed-width font required)
    12     char[]  marker = new char[str.length()];
    13     Arrays.fill(marker,' ');
    14    //  So we can later replace spaces with marker characters
    15 
    16     //  Obtain the required matcher
    17     Pattern pattern = Pattern.compile(regEx);
    18     Matcher m = pattern.matcher(str);
    19 
    20     // Find every match and mark it
    21     while( m.find() ){
    22       System.out.println("Pattern found at Start: "+m.start()+" End: "+m.end());
    23       Arrays.fill(marker,m.start(),m.end(),'^');
    24     }
    25 
    26     // Show the object string with matches marked under it
    27     System.out.println(str);
    28     System.out.println(marker);
    29   }
    30 }
  • 相关阅读:
    C++实现数字媒体三维图像渲染
    C++实现数字媒体三维图像变换
    C++实现数字媒体二维图像变换
    C++实现glut绘制点、直线、多边形、圆
    语音识别之梅尔频谱倒数MFCC(Mel Frequency Cepstrum Coefficient)
    Java中的BigDecimal类精度问题
    spring 手册
    bootstrap 参考文档
    springBoot入门文章
    JNDI
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3440137.html
Copyright © 2011-2022 走看看