Matcher.find()的工作原理 [英] How Matcher.find() works
问题描述
我正在测试一个Matcher和Pattern类的小存根...请看下面的小存根..
I am testing a small stub of Matcher and Pattern class...see the following small stub..
package scjp2.escape.sequence.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sample_19 {
public static void main(String a[]){
String stream = "ab34ef";
Pattern pattern = Pattern.compile("\\d*");
//HERE * IS GREEDY QUANTIFIER THAT LOOKS FOR ZERO TO MANY COMBINATION THAT
//START WITH NUMBER
Matcher matcher = pattern.matcher(stream);
while(matcher.find()){
System.out.print(matcher.start()+matcher.group());
}
}
}
此处。我们比较的字符串是ab34ef。长度为6。
Here ...our string which we are comparing is "ab34ef". which is of length 6.
Noe让我们看看迭代......
Noe let see the iteration...
1 0
2 1
3 2 34
4 4
5 5
现在..let结合... matcher.start()+ matcher.group()....
我们计算的输出是:0123445
Now ..let combine...matcher.start() + matcher.group().... the output as per our calculation is : 0123445
但是,存根生成01234456。
But, the stub generates 01234456.
I我无法理解6的来源。
字符串索引从零开始,所以这里可以有最大索引是5.So从哪里开始?
I am not able to understand from where the "6" is coming. String index starts from zero and so here there can be maximum index is 5.So from where 6 is coming??
它迭代循环六次..怎么样 ?
有什么建议吗?
It iterates over the loop six times..How ? Any suggestion ?
推荐答案
你的正则表达式可以匹配零个字符。最后一个匹配是在字符串末尾出现的零宽度字符串,在索引5处的字符之后。因此,此零宽度字符串的索引为6.
Your regular expression can match zero characters. The final match is a zero width string occurring at the end of the string, after the character at index 5. The index of this zero width string is therefore 6.
另外,如果使用分隔符使输出更具可读性,您可能还会发现更容易理解发生了什么:
As an aside, you might also find it easier to understand what is going on if you use separators to make the output more readable:
System.out.println(matcher.start()+ ": " + matcher.group());
结果:
0:
1:
2: 34
4:
5:
6:
这篇关于Matcher.find()的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!