Getting multiple matches via regex

前端 未结 2 831
-上瘾入骨i
-上瘾入骨i 2021-01-21 22:07

I want to retrieve a strings from a global string via Matcher & Pattern using REGEX.

String str = \"ABC123DEF<         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 22:48

    You need a non greedy regex:

    Pattern pattern = Pattern.compile(".*?");
    

    Use ? to specify non greedy. This means it will match the first match it finds instead of the outer most match...

    If you only want ABC and DEF then you can do something like this using lookaheads and lookbehinds:

    String str = "ABC123DEF";
    Pattern pattern = Pattern.compile("((?<=).*?(?=))");
    Matcher matcher = pattern.matcher(str);
    while(matcher.find())
    {
        System.out.println(matcher.group());
    }
    

    If you do a google search you should be able to find information on lookaheads and lookbehinds...

提交回复
热议问题