I\'m trying to get the last result of a match without having to cycle through .find()
Here\'s my code:
String in = \"num 123 num 1 num 698 num 19238
This seems like a more equally plausible approach.
public class LastMatchTest {
public static void main(String[] args) throws Exception {
String target = "num 123 num 1 num 698 num 19238 num 2134";
Pattern regex = Pattern.compile("(?:.*?num.*?(\\d+))+");
Matcher regexMatcher = regex.matcher(target);
if (regexMatcher.find()) {
System.out.println(regexMatcher.group(1));
}
}
}
The .*?
is a reluctant match so it won't gobble up everything. The ?:
forces a non-capturing group so the inner group is group 1. Matching multiples in a greedy fashion causes it to match across the entire string until all matches are exhausted leaving group 1 with the value of your last match.