3

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?

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102

3 Answers3

2

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

To extract a word after the last . per your instruction you could do this without Pattern and Matcher as following:

String input = "abc.def.ghi.jkl.mno";
String getMe = input.substring(input.lastIndexOf(".")+1, input.length());
System.out.println(getMe);
MS90
  • 1,219
  • 1
  • 8
  • 17
  • 1
    I agree with this. .matches returns a boolean, so it will only tell you if there is a match or not. You could still use matches to confirm if there are any '.' characters at all, and then use the code above to extract. – MGT Mar 28 '19 at 23:48
0

This will work. Use .* at the beginning to enable it to match the entire input.

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

This is a better pattern if the dot really is anywhere: ".*\\.([^.]+)$"

Chloe
  • 25,162
  • 40
  • 190
  • 357