我有以下示例的问题:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
和命令行:
java Regex2 "\d*" ab34ef
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下,为什么结果是:01234456
正则表达式是d* - 它意味着第一或更多,但在args [1]中有更多的位置,
谢谢
Roh*_*ain 10
\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)
Run Code Online (Sandbox Code Playgroud)
如果您使用\\d+,那么您将只获得一个组34.
| 归档时间: |
|
| 查看次数: |
1088 次 |
| 最近记录: |