简体   繁体   English

Java:模式匹配器方法返回错误结果

[英]Java: pattern matcher method returns wrong result

I have tried really hard to understand this, but I just don't get it. 我真的很努力地理解这一点,但是我不明白。 I don't understand why the start() method returns "456" after the group() method returns "34". 我不明白为什么在group()方法返回“ 34”之后start()方法返回“ 456”。

Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
while(m.find())
{
    System.out.print(m.start()+m.group());  // output: 01234456
}

Regex explained 正则表达式解释

Your regex finds 0 length items,which adds a lot of matches of 0 length. 您的正则表达式找到0个长度的项目,这增加了很多0个长度的匹配项。

Explained 解释

As the output is all on 1 line I split it to make it more readable. 由于输出全部在1行上,因此我将其拆分以使其更具可读性。

Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
while(m.find()) {
    System.out.printf("start:%s end:%s text:'%s'%n", m.start(), m.end(), m.group());
}

Output: 输出:

start:0 end:0 text:''
start:1 end:1 text:''
start:2 end:4 text:'34'
start:4 end:4 text:''
start:5 end:5 text:''
start:6 end:6 text:''

This matches your output of 01234456 : 这与您的01234456的输出匹配:

  • 0, 1 and 2 are all group starts 0、1和2都是分组开始
  • 34 is the match text 比赛文字是34
  • 4, 5 and 6 are all group starts 4、5和6都是小组开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM