Find the last match with Java regex matcher

后端 未结 11 2273
情书的邮戳
情书的邮戳 2020-12-01 14:27

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          


        
11条回答
  •  悲&欢浪女
    2020-12-01 15:03

    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.

提交回复
热议问题