贪婪模式和非贪婪模式

 1 package regex;
 2 
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 public class regexDemo {
 7     public static void main(String[] args) {
 8         String str1 = "19900330199012121990111119900220";
 9         String str = "((\d{4})(\d{2})(\d{2}))";
10         Pattern p = Pattern.compile(str);
11         Matcher m = p.matcher(str1);
12 
13         while (m.find()) {
14             // group分组左括号优先匹配。
15             System.out.print("出生日期" + m.group(1));
16             System.out.print("....");
17             System.out.print("出生年" + m.group(2) + " ");
18             System.out.print("出生月" + m.group(3) + " ");
19             System.out.print("出生日" + m.group(4) + " ");
20             // 返回以前匹配的初始索引。
21             System.out.print("start:" + m.start() + " ");
22             // 返回匹配后的位置。
23             System.out.println("end:" + m.end());
24         }
25         
26         String str2 = "<table><td>鱼鱼枫</td><td>这个选手</td><td>野路子</td></table>";
27         //贪婪模式,指的是.*会匹配所有的信息,此处会找整个信息。
28         p = Pattern.compile("<td>(.*)</td>");
29         m = p.matcher(str2);
30         while(m.find()){
31             System.out.println(m.group(1));
32         }
33         //找到的结果:鱼鱼枫</td><td>这个选手</td><td>路子野
34         
35         //非贪婪模式,仅仅只是匹配第一个结果,*?表示使用非贪婪模式
36                 p = Pattern.compile("<td>(.*?)</td>");
37                 m = p.matcher(str2);
38                 while(m.find()){
39                     System.out.print(m.group(1));
40                     System.out.print("start:" + m.start() + " ");
41                     // 返回匹配后的位置。
42                     System.out.println("end:" + m.end());
43                 }
44                 //找到的结果:鱼鱼枫</td><td>这个选手</td><td>路子野
45     }
46 }
原文地址:https://www.cnblogs.com/Akke/p/5008989.html