查找与 Java 正则表达式匹配器的最后一个匹配项

2022-09-01 16:59:11

我试图获得匹配的最后一个结果,而不必循环通过.find()

这是我的代码:

String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num ([0-9]+)");
Matcher m = p.matcher(in);

if (m.find()) {
     in = m.group(1);
}

这将给我第一个结果。如何在不循环浏览潜在巨大列表的情况下找到最后一场比赛?


答案 1

您可以预先附加到正则表达式,这将贪婪地消耗直到最后一个匹配的所有字符:.*

import java.util.regex.*;

class Test {
  public static void main (String[] args) {
    String in = "num 123 num 1 num 698 num 19238 num 2134";
    Pattern p = Pattern.compile(".*num ([0-9]+)");
    Matcher m = p.matcher(in);
    if(m.find()) {
      System.out.println(m.group(1));
    }
  }
}

指纹:

2134

您还可以反转字符串以及更改正则表达式以匹配相反的正则表达式:

import java.util.regex.*;

class Test {
  public static void main (String[] args) {
    String in = "num 123 num 1 num 698 num 19238 num 2134";
    Pattern p = Pattern.compile("([0-9]+) mun");
    Matcher m = p.matcher(new StringBuilder(in).reverse());
    if(m.find()) {
      System.out.println(new StringBuilder(m.group(1)).reverse());
    }
  }
}

但是这两种解决方案都不比仅仅使用 IMO 遍历所有匹配更好。while (m.find())


答案 2

为了获得最后一场比赛,即使这有效,也不确定为什么前面没有提到这一点:

String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num '([0-9]+) ");
Matcher m = p.matcher(in);
if (m.find()) {
  in= m.group(m.groupCount());
}