【轉】Regex貪婪與非貪婪模式

來源:互聯網
上載者:User

標籤:

轉自:http://www.cnblogs.com/xudong-bupt/p/3586889.htmlRegex貪婪與非貪婪模式

之前做程式的時候看到過Regex的貪婪與非貪婪模式,今天用的時候就想不起來了,現在這裡總結一下,以備自己以後用到注意。

1.什麼是Regex的貪婪與非貪婪匹配

  如:String str="abcaxc";

    Patter p="ab*c";

  貪婪匹配:Regex一般趨向於最大長度匹配,也就是所謂的貪婪匹配。如上面使用模式p匹配字串str,結果就是匹配到:abcaxc(ab*c)。

  非貪婪匹配:就是匹配到結果就好,就少的匹配字元。如上面使用模式p匹配字串str,結果就是匹配到:abc(ab*c)。

2.編程中如何區分兩種模式

  預設是貪婪模式;在量詞後面直接加上一個問號?就是非貪婪模式。

  量詞:{m,n}:m到n個

     *:任意多個

     +:一個到多個

     ?:0或一個

3.程式執行個體

使用Snort的規則一條規則的一部分作為匹配文本,匹配出其中的content部分。

 1 import java.util.regex.Matcher; 2 import java.util.regex.Pattern; 3  4 public class RegularTest { 5      6     public static void main(String[] arg){ 7         String text="(content:\"rcpt to root\";pcre:\"word\";)"; 8         String rule1="content:\".+\"";    //貪婪模式 9         String rule2="content:\".+?\"";    //非貪婪模式10         11         System.out.println("文本:"+text);12         System.out.println("貪婪模式:"+rule1);13         Pattern p1 =Pattern.compile(rule1);14         Matcher m1 = p1.matcher(text);15         while(m1.find()){16             System.out.println("匹配結果:"+m1.group(0));17         }18         19         System.out.println("非貪婪模式:"+rule2);20         Pattern p2 =Pattern.compile(rule2);21         Matcher m2 = p2.matcher(text);22         while(m2.find()){23             System.out.println("匹配結果:"+m2.group(0));24         }25     }26 }

執行結果:

 4.注意

  在linux C 下面沒有編譯成功使用?號的非貪婪模式。

   網上的一句話:the ? only works for Perl-based regexp, not for POSIX...

【轉】Regex貪婪與非貪婪模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.