徐州企业做网站,广州市天气,颍上建设局网站,优动网站1.什么是正则表达式的贪婪与非贪婪匹配 如#xff1a;String strabcaxc; Patter pab*c; 贪婪匹配:正则表达式一般趋向于最大长度匹配#xff0c;也就是所谓的贪婪匹配。如上面使用模式p匹配字符串str#xff0c;结果就是匹配到#xff1a;abcaxc(a… 1.什么是正则表达式的贪婪与非贪婪匹配 如String strabcaxc; Patter pab*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 rule1content:\.\; //贪婪模式 String rule2content:\.?\; //非贪婪模式 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次以上但尽可能少重复 参考文章