OCP 7 II正则表达式

时间:2015-01-03 14:40:31

标签: java regex

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

3 个答案:

答案 0 :(得分:2)

@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+,则只有具有一个或多个整数的组才会匹配。

答案 1 :(得分:1)

\d* means integer 0 or more times.So an empty string between a and b ,before a ...those are also

matched.Use `\d+` to get correct result.

参见演示。

https://www.regex101.com/r/fG5pZ8/25

答案 2 :(得分:0)

因为\\d*表示零个或多个数字。

如,

enter image description here