Create array of regex matches

后端 未结 6 1546
醉话见心
醉话见心 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:34

    Here's a simple example:

    Pattern pattern = Pattern.compile(regexPattern);
    List list = new ArrayList();
    Matcher m = pattern.matcher(input);
    while (m.find()) {
        list.add(m.group());
    }
    

    (if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray())

提交回复
热议问题