Java 正则表达式:使用 Matcher.matches() 查找最后一次出现的字符串

Java regex : find the last occurrence of a string using Matcher.matches()

我有以下输入字符串:

abc.def.ghi.jkl.mno

输入中的点字符数可能会有所不同。我想提取最后一个 . 之后的单词(即上例中的 mno )。我正在使用以下 regex 并且它工作得很好:

String input = "abc.def.ghi.jkl.mno";
Pattern pattern = Pattern.compile("([^.]+$)");
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
    System.out.println(matcher.group(1));
}

但是,我正在使用第三方库来执行此匹配(准确地说是 Kafka Connect),我可以只向它提供正则表达式模式。问题是,这个库(我无法更改其代码)使用 matches() 而不是 find() 来进行匹配,当我使用 matches() 执行相同的代码时,它不会t 工作例如:

String input = "abc.def.ghi.jkl.mno";
Pattern pattern = Pattern.compile("([^.]+$)");
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
    System.out.println(matcher.group(1));
}

上面的代码没有打印任何东西。根据 javadocmatches() 尝试匹配整个字符串。有什么方法可以使用 matches() 应用类似的逻辑从我的输入字符串中提取 mno

要根据您的说明在最后一个 . 之后提取单词,您可以在没有模式和匹配器的情况下执行此操作,如下所示:

String input = "abc.def.ghi.jkl.mno";
String getMe = input.substring(input.lastIndexOf(".")+1, input.length());
System.out.println(getMe);

这行得通。在开头使用.*使其能够匹配整个输入。

public static void main(String[] argv) {
    String input = "abc.def.ghi.jkl.mno";
    Pattern pattern = Pattern.compile(".*([^.]{3})$");
    Matcher matcher = pattern.matcher(input);
    if(matcher.matches()) {
        System.out.println(matcher.group(0));
        System.out.println(matcher.group(1));
    }
}

abc.def.ghi.jkl.mno
mno

如果点真的在任何地方,这是一个更好的模式:".*\.([^.]+)$"

您可以使用

".*\.([^.]*)"

匹配

  • .*\. - 任何 0+ 个字符,尽可能多,直到最后一个 . 个字符
  • ([^.]*) - 捕获第 1 组:除点以外的任何 0+ 个字符。

查看 regex demo 和 Regulex 图: