观察正则表达式中3种quantifiers的不同

import java.util.regex.*;

public class RegQuantifiers{
    
    public static void main(String[] args){
        greedy();
        reluctant();
        possessive();
    }
    
    public static void greedy(){
        Pattern p = Pattern.compile(".{2,8}[0-9]");
        Matcher m = p.matcher("sdf5gsf4");
        if(m.find()){
            System.out.println(m.start() + "-" + m.end());
        }else{
            System.out.println("not match!");
        }
    }
    
    public static void reluctant(){
        Pattern p = Pattern.compile(".{3,8}?[0-9]");
        Matcher m = p.matcher("sdf5gsf4");
        if(m.find()){
            System.out.println(m.start() + "-" + m.end());
        }else{
            System.out.println("not match!");
        }
    }
    
    public static void possessive(){
        Pattern p = Pattern.compile(".{3,8}+[0-9]");
        Matcher m = p.matcher("sdf5gsf4");
        if(m.find()){
            System.out.println(m.start() + "-" + m.end());
        }else{
            System.out.println("not match!");
        }
    }
}

 

posted @ 2020-04-02 17:42  yxfyg  阅读(170)  评论(0)    收藏  举报