我对以下示例有疑问:
import java.util.regex.*;
class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + m.group());
}
}
}
还有命令行:
java Regex2 "\d*" ab34ef
谁能给我解释一下,为什么结果是:01234456
正则表达式模式是 d* - 它表示第一个或多个但在 args[1] 中还有更多位置
谢谢
最佳答案
\d*
匹配 0 个或多个数字。因此,它甚至会匹配每个字符之前和最后一个字符之后的空字符串。首先在索引 0
之前,然后在索引 1
之前,依此类推。
因此,对于字符串 ab34ef
,它匹配以下组:
Index Group
0 "" (Before a)
1 "" (Before b)
2 34 (Matches more than 0 digits this time)
4 "" (Before `e` at index 4)
5 "" (Before f)
6 "" (At the end, after f)
如果您使用 \\d+
,那么您将在 34
处得到一个组。
关于java - SCJP6 正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384930/