我需要帮助来理解下面代码的输出.我无法找出输出System.out.print(m.start() + m.group());.请有人向我解释一下吗?
import java.util.regex.*;
class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
boolean b = false;
while(b = m.find()) {
System.out.println(m.start() + m.group());
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0
1
234
4
5
6
Run Code Online (Sandbox Code Playgroud)
请注意,如果我放System.out.println(m.start() );,输出是:
0
1
2
4
5
6
Run Code Online (Sandbox Code Playgroud)
因为您已经包含了一个*字符,所以您的模式也会匹配空字符串.当我按照我在评论中建议更改您的代码时,我得到以下输出:
0 ()
1 ()
2 (34)
4 ()
5 ()
6 ()
Run Code Online (Sandbox Code Playgroud)
所以你有大量的空匹配(匹配字符串中的每个位置),除了34匹配数字字符串.使用\\d+,如果你想也没有匹配空字符串匹配的数字..
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |