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
Use negative lookahead:
String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num (\\d+)(?!.*num \\d+)");
Matcher m = p.matcher(in);
if (m.find()) {
in= m.group(1);
}
The regular expression reads as "num followed by one space and at least one digit without any (num followed by one space and at least one digit) at any point after it".
You can get even fancier by combining it with positive lookbehind:
String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("(?<=num )\\d+(?!.*num \\d+)");
Matcher m = p.matcher(in);
if (m.find()) {
in = m.group();
}
That one reads as "at least one digit preceded by (num and one space) and not followed by (num followed by one space and at least one digit) at any point after it".
That way you don't have to mess with grouping and worry about the potential IndexOutOfBoundsException
thrown from Matcher.group(int)
.