This question already has an answer here:
Regular expression - Greedy quantifier [duplicate]
                                
                                    (1个答案)
                                
                        
                                4年前关闭。
            
                    
import java.util.regex.*;

public class Regex2 {

    public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d*");
        Matcher m = p.matcher("ab34ef");
        boolean b = false;
        while ( m.find()) {
            System.out.print(m.start() + m.group());
        }
    }
}


为什么此代码产生输出:01234456

最佳答案

@vks是正确的:
如果您使用的是\\d*,则适用于每个字符:

Index: char = matching:
    0: 'a'  = "" because no integer
    1: 'b'  = "" because no integer
    2: '3'  = "34" because there is two integer between index [2-3]
       '4'    is not checked because the index has been incremented in previous check.
    4: 'e'  = ""
    5: 'f'  = "" because no integer
    6: ''   = "" IDK


它产生0,“”,1,“”,2,“ 34”,4,“”,5,“”,6,“” = 01234456(这就是为什么得到它)。

如果使用\\d+,则只有具有一个或多个整数的组将匹配。

08-06 20:02