【问题标题】:pattern search using regex in java在java中使用正则表达式进行模式搜索
【发布时间】:2012-12-26 18:16:33
【问题描述】:
public static void main(String args[]) {
    Pattern p = Pattern.compile("ab");  // Case 1
    Pattern p = Pattern.compile("bab");  // Case 2
    Matcher m = p.matcher("abababa");
    while(m.find()){
        System.out.print(m.start());
    }
}

当我使用 Case 1 时,输出结果如预期的那样是 024。但是,当我使用 Case 2 时,输出为 1,但预期为 13。所以,任何人解释我,regex 中是否有任何异常规则,如果没有,会导致此输出。然后,为什么我得到这个输出。

帮助赞赏!!

注意:案例 1 和案例 2 是独立使用的。

【问题讨论】:

    标签: java regex pattern-matching matcher


    【解决方案1】:

    匹配消耗输入,所以下一个匹配是在上一个匹配结束之后找到的:

    每次匹配前“bab”匹配器指针的位置是:

    1. |abababa
    2. abab|aba

    【讨论】:

      【解决方案2】:

      对于案例 2:

      这是因为,在搜索 bab 之后,它不会考虑已经搜索过的字符(在这种情况下为索引 3 处的 b),因此您只会得到 1。

      Input:  abababa
      Search for bab, 
       find's a match starting at index 1 and ending at index 3, next the search would start at index 4(aba)
      

      【讨论】:

        猜你喜欢
        • 2014-10-21
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 2016-07-19
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多