OCP 7 II 正则表达式
OCP 7 II regular expression
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
\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.
查看演示。
@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+
,则只有具有一个或多个整数的组才会匹配。
因为\d*
表示零个或多个数字。
作为,
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
\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.
查看演示。
@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+
,则只有具有一个或多个整数的组才会匹配。
因为\d*
表示零个或多个数字。
作为,