zoukankan      html  css  js  c++  java
  • JAVA程序中使用正则表达式

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    /**
    * @author Administrator 测试正则表达式
    *
    */
    public class TestRegex {

       /**
        * alt+shift+j
        *
        * @param args
      */
    public static void main(String[] args) {

       /**
        * 使用 正则表达式的 方式与步骤 通过Pattern的实例 得到 正则表达式的匹配器 Matcher
        *
      */

      // 得到 Pattern实例
      // Pattern pattern = Pattern.compile("(\w{3})(\w{3})");

      // Pattern.CASE_INSENSITIVE 不区分大小写
      Pattern pattern = Pattern.compile("([abcdef]{3})([abcdef]{3})",
      Pattern.CASE_INSENSITIVE);

      // 得到匹配器

      Matcher matcher = pattern.matcher("abcDefg");
      // matches 进行全局匹配 与给定的字符串进行全匹配
      boolean b = matcher.matches();

      System.out.println(b);

      matcher.reset();

      System.out.println("-------------------");
      // 得到查找到的值

      // 要得到值 就一定要先find
      while (matcher.find()) {
      // 关于得到值
      // 如果 不传值 相当于 调用了group(0) 如果要得到相应的组里面的值 则传入相应的组号
     System.out.println(matcher.group());
    }
    // matcher.find();

    System.out.println(contains("\w", "[]"));

    }

    /**
    * 根据给定的正则表达式去判断原字符串中是有含有匹配的子字符串
    *
    * @param regex
    * 给定的正则表达式
    * @param src
    * 给定的输入原
    * @return 返回结果
    */
    public static boolean contains(String regex, String src) {
    // 创建一个模式
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(src);
    return matcher.find();
    }

    }

  • 相关阅读:
    SGU 271 Book Pile (双端队列)
    POJ 3110 Jenny's First Exam (贪心)
    HDU 4310 Hero (贪心)
    ZOJ 2132 The Most Frequent Number (贪心)
    POJ 3388 Japanese Puzzle (二分)
    UVaLive 4628 Jack's socks (贪心)
    POJ 2433 Landscaping (贪心)
    CodeForces 946D Timetable (DP)
    Android Studio教程从入门到精通
    Android Tips – 填坑手册
  • 原文地址:https://www.cnblogs.com/hwgok/p/5746909.html
Copyright © 2011-2022 走看看