Create array of regex matches

后端 未结 6 1620
醉话见心
醉话见心 2020-11-22 16:21

In Java, I am trying to return all regex matches to an array but it seems that you can only check whether the pattern matches something or not (boolean).

How can I u

6条回答
  •  不要未来只要你来
    2020-11-22 16:46

    In Java 9, you can now use Matcher#results() to get a Stream which you can use to get a list/array of matches.

    import java.util.regex.Pattern;
    import java.util.regex.MatchResult;
    
    String[] matches = Pattern.compile("your regex here")
                              .matcher("string to search from here")
                              .results()
                              .map(MatchResult::group)
                              .toArray(String[]::new);
                        // or .collect(Collectors.toList())
    

提交回复
热议问题