正则表达式补充内容测试

故事扮演 提交于 2020-04-02 21:25:45
import java.util.regex.*;

public class RegPlus{
    
    public static void main(String[] args){
        //group();
        //reference();
        flags();
    }
    
    //non-capturing groups
    private static void group(){
        String str = "drfajian";
        Pattern p1 = Pattern.compile("[a-z]{3}(?=a)");
        Pattern p2 = Pattern.compile("(?=a)[a-z]{3}");
        Pattern p3 = Pattern.compile("[a-z]{3}(?!a)");
        Pattern p4 = Pattern.compile("(?!a)[a-z]{3}");
        Matcher m1 = p1.matcher(str);
        Matcher m2 = p2.matcher(str);
        Matcher m3 = p3.matcher(str);
        Matcher m4 = p4.matcher(str);
        
        while(m1.find()){
            System.out.print(m1.group() + " ");
        }
        
        System.out.println();
        
        while(m2.find()){
            System.out.print(m2.group() + " ");
        }
        
        System.out.println();
        
        while(m3.find()){
            System.out.print(m3.group() + " ");
        }
        
        System.out.println();
        
        while(m4.find()){
            System.out.print(m4.group() + " ");
        }
        
        System.out.println();
    }
    
    //back references    向前引用
    private static void reference(){
        String str1 = "3232";
        String str2 = "322";
        Pattern p1 = Pattern.compile("(\\d\\d)\\1");
        Pattern p2 = Pattern.compile("(\\d(\\d))\\2");
        Matcher m1 = p1.matcher(str1);
        Matcher m2 = p2.matcher(str2);
      System.out.println(m1.matches());
      System.out.println(m2.matches());
    }
    
    //flags的简写
    
    private static void flags(){
        Pattern p1 = Pattern.compile("java",Pattern.CASE_INSENSITIVE);
        Pattern p2 = Pattern.compile("(?i)(java)");//两种写法一样,?i表示打开标志位
        Matcher m1 = p1.matcher("JAva");
        Matcher m2 = p2.matcher("JAva");
        System.out.println(m1.matches());
      System.out.println(m2.matches());
    }
    
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!