正则表达式贪婪与非贪婪模式

1.什么是正则表达式的贪婪与非贪婪匹配
  如:String str="abcaxc";
    Patter p="ab.*c";
  贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。如上面使用模式p匹配字符串str,结果就是匹配到:abcaxc(ab.*c)。
  非贪婪匹配:就是匹配到结果就好,就少的匹配字符。如上面使用模式p匹配字符串str,结果就是匹配到:abc(ab.*c)。
2.编程中如何区分两种模式
  默认是贪婪模式;在量词后面直接加上一个问号?就是非贪婪模式。
  量词:{m,n}:m到n个
     *:任意多个
     +:一个到多个
     ?:0或一个
3.程序实例

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

public class RegularTest {
    
    public static void main(String[] arg){
        String text="(content:\"rcpt to root\";pcre:\"word\";)";
        String rule1="content:\".+\"";    //贪婪模式
        String rule2="content:\".+?\"";    //非贪婪模式
        
        System.out.println("文本:"+text);
        System.out.println("贪婪模式:"+rule1);
        Pattern p1 =Pattern.compile(rule1);
        Matcher m1 = p1.matcher(text);
        while(m1.find()){
            System.out.println("匹配结果:"+m1.group(0));
        }
        
        System.out.println("非贪婪模式:"+rule2);
        Pattern p2 =Pattern.compile(rule2);
        Matcher m2 = p2.matcher(text);
        while(m2.find()){
            System.out.println("匹配结果:"+m2.group(0));
        }
    }
}

执行结果:

 4.例题:

Java中用正则表达式截取字符串中第一个出现的英文左括号之前的字符串。比如:北京市(海淀区)(朝阳区)(西城区),截取结果为:北京市。正则表达式为()

答:".*?(?=\\()"
  解析:(?=Expression) 顺序环视,(?=\\()就是匹配正括号
  懒惰模式正则: 
  src=".*? (?=\\() "
  结果:北京市
  因为匹配到第一个"就结束了一次匹配。不会继续向后匹配。因为他懒惰嘛。
posted @ 2019-01-11 17:05  Archer-Fang  阅读(346)  评论(0编辑  收藏  举报