【问题标题】:Matcher Find nth Match Indexes匹配器查找第 n 个匹配索引
【发布时间】:2013-01-10 08:20:19
【问题描述】:

我正在尝试获取在文档中找到的每个模式的索引。到目前为止,我有:

    String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
    Pattern pattern = Pattern.compile("HelloWorld");
    Matcher matcher = pattern.matcher(temp);
    int current = 0;
    int start;
    int end;

    while (matcher.find()) {
        start = matcher.start(current);
        end = matcher.end(current);
        System.out.println(temp.substring(start, end));
        current++;
    }

出于某种原因它一直只在temp 中找到HelloWorld 的第一个实例,但这会导致无限循环。老实说,我不确定你是否可以使用matcher.start(current)matcher.end(current) - 这只是一个疯狂的猜测,因为matcher.group(current) 以前工作过。这次我需要实际的索引,所以 matcher.group() 对我不起作用。

【问题讨论】:

    标签: java regex pattern-matching


    【解决方案1】:

    修改正则表达式,如下所示:

    while (matcher.find()) {
        start = matcher.start();
        end = matcher.end();
        System.out.println(temp.substring(start, end));
    }
    

    【讨论】:

      【解决方案2】:

      不要将索引传递给start(int)end(int)。 API 声明参数是组号。在您的情况下,只有零是正确的。请改用start()end()

      由于您对find() 的调用,匹配器将在每次迭代中移动到下一个匹配项:

      此方法从输入序列的开头开始,或者,如果之前对该方法的调用成功并且匹配器尚未重置,则从前一个匹配不匹配的第一个字符开始。

      【讨论】:

        【解决方案3】:

        问题是这行代码。

         start = matcher.start(current);
        

        current 在第一次迭代后为 1。

        【讨论】:

          【解决方案4】:

          如果您只需要匹配文本的开始和结束偏移量,则不需要当前组,这样就可以了:

              String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
              Pattern pattern = Pattern.compile("HelloWorld");
              Matcher matcher = pattern.matcher(temp);
              int current = 0;
          
              while (matcher.find()) {
                  System.out.println(temp.substring(matcher.start(), matcher.end()));
              }
          

          【讨论】:

            【解决方案5】:
            while (matcher.find()) {
                start = matcher.start();
                end = matcher.end();
                System.out.println(temp.substring(start, end));
            }
            

            会做你想做的。

            【讨论】:

              【解决方案6】:
                  String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
                  Pattern pattern = Pattern.compile("HelloWorld");
                  Matcher m = pattern.matcher(temp);
                  while (matcher.find()) {
                      System.out.println(temp.substring(m.start(), m.stop()));
                  }
              

              【讨论】:

                猜你喜欢
                • 2019-09-30
                • 2017-02-23
                • 1970-01-01
                • 1970-01-01
                • 2020-08-02
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-11-01
                相关资源
                最近更新 更多