- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class RegexDemo2 {
- public static void main(String args[]) {
- Demo2();
- }
- private static void getDemo() {
- // TODO Auto-generated method stub
- String str = "ming tian jiuyao fang jia le,da jia";
- String reg = "\\b[a-z]{4}\\b";
- Pattern p = Pattern.compile(reg);
- Matcher m = p.matcher(str);
- while (m.find()) {
- System.out.println(m.group());
- System.out.println(m.start() + "..." + m.end());
- }
- }
- private static void Demo2() {
- String str="008.109.090.030";
- String reg="0+(\\d+)";//Greedy 数量词
- Pattern p=Pattern.compile(reg);
- Matcher m=p.matcher(str);
- while( m.find() ){
- System.out.print(m.group()+"--->");
- int len= m.groupCount();
- System.out.print(len+"-----");
- for(int i=0;i<=1;i++){
- System.out.print("group"+"("+i+"):"+m.group(i)+" ");
- }
- System.out.println(" ");
- }
- System.out.println("++++++++++++++++++++++++++++++++++++++");
-
- String str1="008.109.090.030";
- String reg1="0+(\\d+?)";//Reluctant 数量词
- Pattern p1=Pattern.compile(reg1);
- Matcher m1=p1.matcher(str1);
- while( m1.find() ){
- System.out.print(m1.group()+"--->");
- int len= m1.groupCount();
- System.out.print(len+"-----");
- for(int i=0;i<=1;i++){
- System.out.print("group"+"("+i+"):"+m1.group(i)+" ");
- }
- System.out.println(" ");
- }
-
-
- }
- }
- 结果:
- 008--->1-----group(0):008 group(1):8
- 09--->1-----group(0):09 group(1):9
- 090--->1-----group(0):090 group(1):90
- 030--->1-----group(0):030 group(1):30
- ++++++++++++++++++++++++++++++++++++++
- 008--->1-----group(0):008 group(1):8
- 09--->1-----group(0):09 group(1):9
- 09--->1-----group(0):09 group(1):9
- 03--->1-----group(0):03 group(1):3
复制代码
为什么会有这样不同的结果? |
|