正则表达式贪婪与非贪婪模式
之前做程序的时候看到过正则表达式的贪婪与非贪婪模式,今天用的时候就想不起来了,现在这里总结一下,以备自己以后用到注意。
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.程序实例
使用Snort的规则一条规则的一部分作为匹配文本,匹配出其中的content部分。
1 import java.util.regex.Matcher; @H_301_65@ 2 import java.util.regex.Pattern; @H_301_65@ 3 @H_301_65@ 4 public class RegularTest { @H_301_65@ 5 @H_301_65@ 6 static void main(String[] arg){ @H_301_65@ 7 String text="(content:\"rcpt to root\";pcre:\"word\";)"; @H_301_65@ 8 String rule1="content:\".+\""; //贪婪模式 @H_301_65@ 9 String rule2="content:\".+?\""; 非贪婪模式 @H_301_65@10 @H_301_65@11 System.out.println("文本:"+text); @H_301_65@12 System.out.println("贪婪模式:"+rule1); @H_301_65@13 Pattern p1 =Pattern.compile(rule1); @H_301_65@14 Matcher m1 = p1.matcher(text); @H_301_65@15 while(m1.find()){ @H_301_65@16 System.out.println("匹配结果:"+m1.group(0)); @H_301_65@17 } @H_301_65@18 @H_301_65@19 System.out.println("非贪婪模式:"+rule2); @H_301_65@20 Pattern p2 =Pattern.compile(rule2); @H_301_65@21 Matcher m2 = p2.matcher(text); @H_301_65@22 while(m2.find()){ @H_301_65@23 System.out.println("匹配结果:"+m2.group(0)); @H_301_65@24 } @H_301_65@25 } @H_301_65@26 }执行结果: