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 num 2134"; Pattern p = Pattern.compile("num '([0-9]+) "); Matcher m = p.matcher(in); if (m.find()) { in = m.group(1); }
That will give me the first result. How do I find the LAST match without cycling through a potentionally huge list?
Difference between matches() and find() in Java Regex matcher() method. The matches() method returns true If the regular expression matches the whole text. If not, the matches() method returns false. Whereas find() search for the occurrence of the regular expression passes to Pattern.
The Java Matcher class ( java. util. regex. Matcher ) is used to search through a text for multiple occurrences of a regular expression. You can also use a Matcher to search for the same regular expression in different texts.
Matcher find() method in Java with Examples The find() method of Matcher Class attempts to find the next subsequence of the input sequence that find the pattern. It returns a boolean value showing the same. Syntax: public boolean find() Parameters: This method do not takes any parameter.
You could prepend .*
to your regex, which will greedily consume all characters up to the last match:
import java.util.regex.*; class Test { public static void main (String[] args) { String in = "num 123 num 1 num 698 num 19238 num 2134"; Pattern p = Pattern.compile(".*num ([0-9]+)"); Matcher m = p.matcher(in); if(m.find()) { System.out.println(m.group(1)); } } }
Prints:
2134
You could also reverse the string as well as change your regex to match the reverse instead:
import java.util.regex.*; class Test { public static void main (String[] args) { String in = "num 123 num 1 num 698 num 19238 num 2134"; Pattern p = Pattern.compile("([0-9]+) mun"); Matcher m = p.matcher(new StringBuilder(in).reverse()); if(m.find()) { System.out.println(new StringBuilder(m.group(1)).reverse()); } } }
But neither solution is better than just looping through all matches using while (m.find())
, IMO.
To get the last match even this works and not sure why this was not mentioned earlier:
String in = "num 123 num 1 num 698 num 19238 num 2134"; Pattern p = Pattern.compile("num '([0-9]+) "); Matcher m = p.matcher(in); if (m.find()) { in= m.group(m.groupCount()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With