Search code examples
javaregexregex-greedy

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


I have following input String:

abc.def.ghi.jkl.mno

Number of dot characters may vary in the input. I want to extract the word after the last . (i.e. mno in the above example). I am using the following regex and its working perfectly fine:

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));
}

However, I am using a third party library which does this matching (Kafka Connect to be precise) and I can just provide the regex pattern to it. The issue is, this library (whose code I can't change) uses matches() instead of find() to do the matching, and when I execute the same code with matches(), it doesn't work e.g.:

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));
}

The above code doesn't print anything. As per the javadoc, matches() tries to match the whole String. Is there any way I can apply similar logic using matches() to extract mno from my input String?


Solution

  • You may use

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

    It matches

    • .*\. - any 0+ chars as many as possible up to the last . char
    • ([^.]*) - Capturing group 1: any 0+ chars other than a dot.

    See the regex demo and the Regulex graph:

    enter image description here