【问题标题】:Match Specific Index [duplicate]匹配特定索引 [重复]
【发布时间】:2012-12-30 16:20:45
【问题描述】:

可能重复:
find the nth occurence of a substring in a string in java?

有没有办法在字符串中获得特定的匹配项?

如果我们有String test = "this is a long test which is a test of a test";,那么我们可以使用Matcher 来获取test第二个(或任何特定)实例吗?

我以为我可以使用Matcher.find(x),但这似乎不太好用...

【问题讨论】:

  • @Threat 是否要查找包含单词?
  • 如果您要查找的是文字字符串,则只需使用 indexOf。如果您想找到与正则表达式匹配的第二次出现,那么您还可以使用带有计数器的 Matcher 循环。也可以先使用 Pattern/Matcher 进行查找。
  • @nhahtdh 你也可以在循环中使用indexOf(char, int)
  • @MarkoTopolnik:String 类中没有具有该签名的方法。

标签: java regex string pattern-matching match


【解决方案1】:

试试

int firstIndex = string.indexOf("test");
if (firstIndex >= 0) {
    int secondIndex = string.indexOf("test", firstIndex+1);
}

另外,如果你想要第 n 次出现,你可以循环:

int nthIndex = -1;
for (int i=0; i<n; i++ ) {
    nthIndex = string.indexOf("test", nthIndex +1);
    if (nthIndex < 0) {
        break;
    }
}

这将为您提供 nthIndex,如果未找到,则为 -1。

【讨论】:

    【解决方案2】:

    您可以使用indexOf 方法来做到这一点。

        String string;
        int one = string.indexOf(strToBeSearched);     
        int two = string.indexOf(strToBeSearched, one+1);
    

    此外,您应该检查one 是否>= 0(如果strToBeSearched 不存在于字符串中,indexOf 将返回-1)

    【讨论】:

      【解决方案3】:

      我认为这个函数可以完成这项工作

      int find(String s, String pattern, int occurence) {
          Matcher m = Pattern.compile(pattern).matcher(s);
          for (int i = 1; m.find(); i++) {
              if (i == occurence) {
                  return m.start();
              }
          }
          throw new RuntimeException();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 2017-05-08
        • 2019-02-21
        • 1970-01-01
        • 2017-06-22
        • 2018-01-20
        相关资源
        最近更新 更多