观察正则表达式中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!");
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/yxfyg/p/12621289.html