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 }
  • 相关阅读:
    java spring-WebSocket json参数传递与接收
    java实现zabbix接口开发
    Linux 系统中的MySQL数据库默认区分大小写
    获取Linux下的IP地址 java代码
    Java多线程问题总结
    Easyui之accordion修改Title样式,字体等
    机器学习算法随机数据生成
    神经网络MPLClassifier分类
    给定数据利用神经网络算法模型进行计算
    vue $refs获取dom元素
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3440137.html
Copyright © 2011-2022 走看看