java 正则表达式贪婪与懒惰

java如何运行正则?

  1. String自带的matches()方法验证。但这种验证是调用了Pattern的matches方法。
public boolean matches(String regex) {
          
   
        return Pattern.matches(regex, this);//底层源码
    }
  1. 编译正则表达式
public static void main(String[] args) {
          
   
       String str="efsefsef2@2@2222";
       //?<! 匹配\w+前面跟的不是\d的内容
       String reg="(?<!\d)\w+";
        Pattern pattern=Pattern.compile(reg);//先编译正则
         //再把字符串加入到matcher对象
        Matcher matcher=pattern.matcher(str);
        //开始局部匹配遇到第一个符合条件的就停止匹配
        matcher.find();
        System.out.println(matcher.group());
    }

运行结果: 贪婪与懒惰

  1. 当我们不对*,+,?做处理时他就是贪婪的每次匹配都偏向于多的一方。
public static void main(String[] args) {
          
   
       String str="efsefsef2@2@2222";
        String reg="\w+";   //w 字母数字下划线  ?<=  ?!  ?:

        Pattern pattern=Pattern.compile(reg);

        Matcher matcher=pattern.matcher(str);

        matcher.find();

        System.out.println(matcher.group());
    }

结果:

  1. 当我们想让他懒惰时,让他偏向少的一方可以在后面加上?来让我们试下。
public static void main(String[] args) {
          
   
       String str="efsefsef2@2@2222";
        String reg="\w+?";   //w 字母数字下划线  ?<=  ?!  ?:

        Pattern pattern=Pattern.compile(reg);

        Matcher matcher=pattern.matcher(str);

        matcher.find();

        System.out.println(matcher.group());
    }

结果:

public static void main(String[] args) {
          
   
       String str="efsefsef2@2@2222";
        String reg="\w*?";   //w 字母数字下划线  ?<=  ?!  ?:

        Pattern pattern=Pattern.compile(reg);

        Matcher matcher=pattern.matcher(str);

        matcher.find();

        System.out.println(matcher.group());
    }

结果: 同理其他只要加上?就会变得懒惰。

经验分享 程序员 微信小程序 职场和发展