Java regular expressions: find the last occurrence of a string using Matcher. Match()
I have the following input string:
abc.def.ghi.jkl.mno
The number of dot characters in the input may vary. I want to extract the word after the last . (i.e.
mno
in the example above). I’m using the following regex
and it works just 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’m using a third-party library to perform this match ( Kafka Connect), I can just provide it with regular expression patterns. The problem is that this library (whose code I can’t change) uses matches() instead of find() for matching
, and when I execute the same code with matches()
it doesn’t work for example:
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 code above doesn’t print anything. According to javadoc, matches().
Try to match the entire string. Is there any way to extract mno
from my input string using matches()
applying similar logic?
Solution
You can use
it
".*\\.( [^.] *)"
Match
.*\
. – Any 0+ characters up to the last.
([^.] *)
– Capture Group 1: Any 0+ characters except dots.
character
See regex demo and regular graph