Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last match with Java regex matcher

Tags:

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?

like image 706
kireol Avatar asked Jun 20 '11 20:06

kireol


People also ask

What is difference between matches () and find () in Java regex?

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.

What is regex matcher in Java?

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.

What is find () in Java?

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.


2 Answers

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.

like image 139
Bart Kiers Avatar answered Oct 11 '22 13:10

Bart Kiers


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()); } 
like image 31
araut Avatar answered Oct 11 '22 12:10

araut