Java Regex中的零长度匹配 [英] Zero-length matches in Java Regex

查看:159
本文介绍了Java Regex中的零长度匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

Pattern pattern = Pattern.compile("a?");
Matcher matcher = pattern.matcher("ababa");
while(matcher.find()){
   System.out.println(matcher.start()+"["+matcher.group()+"]"+matcher.end());
}

输出:

0[a]1
1[]1
2[a]3
3[]3
4[a]5
5[]5

我所知道的:


  • a?代表零或一次出现的字符'a'。

Java API说:

Java API says :


  • matcher.start()返回上一个匹配的起始索引。

  • matcher.end()返回最后一个字符匹配后的偏移量。

  • matcher.group()返回与前一个
    匹配匹配的输入子序列。对于具有输入序列s的匹配器m,表达式
    m.group()和s.substring(m.start(),m.end())是等价的。而对于
    ,某些模式(例如a *)与空字符串匹配。当模式成功匹配输入中的空字符串
    时,此方法
    将返回空字符串。

我想知道的是:


  1. 在哪种情况下,正则表达式引擎遇到给定字符的零
    次出现? - 这里是字符'a'。

  2. 在这种情况下,匹配器中的start(),
    end()和group()方法实际返回的值是什么。我已经提到了
    java API所说的内容。但是我不清楚上面的实际
    情况。


推荐答案

是一个贪婪的量词,因此它会在尝试0次出现之前首先尝试匹配1次出现。在你的字符串中,

The ? is a greedy quantifier, therefore it will first try to match the 1-occurence before trying the 0-occurence. In you string,


  1. 它从第一个字符'a'开始,并尝试再次匹配1次出现。 'a'字符匹配,因此它返回您看到的第一个结果

  2. 然后它向前移动并找到'b'。 'b'字符与正则表达式1出现不匹配,因此引擎回溯并尝试匹配0出现。结果是空字符串匹配 - >你得到你的第二个结果。

  3. 然后它移动到b之前,因为那里不再有匹配,并且它再次以你的第二个'a'开始'char。

  4. 等......你明白了......

  1. it starts with the first char 'a' and tries to match agains the 1-occurence. The 'a' char matches and so it returns the first result you see
  2. then it moves forward and find a 'b'. The 'b' char does not match your regexp 1-occurence, so the engine backtracks and attempt to match a 0-occurence. Result is that the empty string is matched--> you get your second result.
  3. then it moves ahead of b since no more matches are possible there and it starts again with your second 'a' char.
  4. etc... you get the point...

这是比这复杂一点,但这是主要的想法。当1次出现不匹配时,它将尝试0次出现。

It is a bit more complicated than that but that is the main idea. When the 1-occurence cannot match, it will then try with the 0-occurence.

至于start,end和group的值,它们将是匹配的位置开始,结束和组是匹配的,所以在你的字符串的第一个0-occurence匹配,你得到1,1和emtpy字符串。我不确定这真的能回答你的问题。

As for the values of start, end and group, they will be where the match starts, ends and the group is what has been matched, so in the first 0-occurence match of your string, you get 1, 1 and the emtpy string. I am not sure this really answers your question.

这篇关于Java Regex中的零长度匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆