python贪婪匹配和非贪婪匹配_贪婪匹配和非贪婪匹配
1.什么是正則表達式的貪婪與非貪婪匹配
如:String str="abcaxc";
Patter p="ab*c";
貪婪匹配:正則表達式一般趨向于最大長度匹配,也就是所謂的貪婪匹配。如上面使用模式p匹配字符串str,結果就是匹配到:abcaxc(ab*c)。
非貪婪匹配:就是匹配到結果就好,就少的匹配字符。如上面使用模式p匹配字符串str,結果就是匹配到:abc(ab*c)。
2.編程中如何區分兩種模式
默認是貪婪模式;在量詞后面直接加上一個問號?就是非貪婪模式。
量詞:{m,n}:m到n個
*:任意多個
+:一個到多個
?:0或一個
demoimport?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));
}
}
}
貪婪匹配:在滿足匹配時,匹配盡可能長的字符串,默認情況下,采用貪婪匹配string?pattern1?=?@"a.*c";???//?greedy?match?Regex?regex?=?new?Regex(pattern1);
regex.Match("abcabc");?//?return?"abcabc"
非貪婪匹配:在滿足匹配時,匹配盡可能短的字符串,使用?來表示非貪婪匹配string?pattern1?=?@"a.*?c";???//?non-greedy?match?Regex?regex?=?new?Regex(pattern1);
regex.Match("abcabc");?//?return?"abc"
幾個常用的非貪婪匹配Pattern*??重復任意次,但盡可能少重復
+??重復1次或更多次,但盡可能少重復
???重復0次或1次,但盡可能少重復
{n,m}??重復n到m次,但盡可能少重復
{n,}??重復n次以上,但盡可能少重復
參考文章:
總結
以上是生活随笔為你收集整理的python贪婪匹配和非贪婪匹配_贪婪匹配和非贪婪匹配的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自然灾害有哪些(最常见的自然灾害)
- 下一篇: 十大美颜软件排行榜,2019最火的拍照软