Java 正则表达式 原

2018-08-14 11:55:19 浏览数 (1)

代码语言:javascript复制
package com.zhaogang.app.web.aspect;

/**
 * Created by weixiang.wu on 2017/9/20.
 */

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

public class RegexMatches {


    public static void main(String args[]) {
//        在表达式((A)(B(C))),有四个这样的组:
//        ((A)(B(C)))
//        (A)
//        (B(C))
//        (C)


        // 按指定模式在字符串查找
        String line = "This order was placed for QT3000! OK?";
        String pattern1 = "(\D*)(\d )(.*)";

        int count1 = 0;

        // 创建 Pattern 对象
        Pattern r1 = Pattern.compile(pattern1);

        // 现在创建 matcher 对象
        Matcher m1 = r1.matcher(line);
        if (m1.find()) {
            for (int i = 0; i <= m1.groupCount(); i  ) {
                count1  ;
                System.out.println("Match number " count1);
                System.out.println("start(): " m1.start());
                System.out.println("end(): " m1.end());
                System.out.println(m1.group(i));
            }
        } else {
            System.out.println("NO MATCH");
        }





        String str = "1234567890";
        String pattern = "((?<=\d)\d{3}) \b";
        int count = 0;

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        if (m.find()) {
            for (int i = 0; i <= m.groupCount(); i  ) {
                count  ;
                System.out.println("Match number " count);
                System.out.println("start(): " m.start());
                System.out.println("end(): " m.end());
                System.out.println(m.group(i));
            }
        } else {
            System.out.println("NO MATCH");
        }



 /** 
   * 获取查询的字符串 
   * 将匹配的字符串取出 
   */
  private void getString(String str, String regx) { 
    //1.将正在表达式封装成对象Patten 类来实现 
    Pattern pattern = Pattern.compile(regx); 
    //2.将字符串和正则表达式相关联 
    Matcher matcher = pattern.matcher(str); 
    //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。 
       
    System.out.println(matcher.matches()); 
    //查找符合规则的子串 
    while(matcher.find()){ 
      //获取 字符串 
      System.out.println(matcher.group()); 
      //获取的字符串的首位置和末位置 
      System.out.println(matcher.start() "--" matcher.end()); 
    } 
  } 


//去除叠词
//reg.getReplace("12111123ASDASDAAADDD","(.)\1 ","$1");
/**
     * 字符串的替换
     */
    private void getReplace(String str, String regx,String replaceStr) {
        String stri = str.replaceAll(regx,replaceStr) ;
        System.out.println("正则表达式替换" stri);
    }


    }
}
代码语言:javascript复制
Match number 1
start(): 0
end(): 37
This order was placed for QT3000! OK?
Match number 2
start(): 0
end(): 37
This order was placed for QT
Match number 3
start(): 0
end(): 37
3000
Match number 4
start(): 0
end(): 37
! OK?
Match number 1
start(): 1
end(): 10
234567890
Match number 2
start(): 1
end(): 10
890

Process finished with exit code 0

0 人点赞