Find the last match with Java regex matcher

后端 未结 11 2215
情书的邮戳
情书的邮戳 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 14:58

    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.

提交回复
热议问题