Java OCP7Ⅱ正则表达式
此代码为何生成输出:01234456Java OCP7Ⅱ正则表达式,java,regex,Java,Regex,此代码为何生成输出:01234456 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(
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());
}
}
}
见演示
@vks是对的:
如果您使用的是\\d*
,则它适用于每个字符:
\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.
它产生0,“,1,”,2,“,34,”,4,“,5,“,6,”=01234456(这就是你得到它的原因)
如果使用
\\d+
则只有具有一个或多个整数的组才会匹配。因为\\d*
表示零或多个数字
作为
如果您使用
println
,您将更清楚地了解发生了什么。
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