Skip to content

Java RegEx – Get Matches Array or ArrayList

Java RegEx – get matches array or ArrayList example shows how to get all regex matches as an array or an ArrayList object in Java.

How to get regex matches as an ArrayList in Java?

In Java RegEx, there is no direct way to get all the matches as an array or an ArrayList. The process goes like first we create a pattern object to match. Then we create a matcher object to match the pattern against the input string. After that, we iterate over matches using the find method of the Matcher class and get the matches using the group method one by one.

However, we can write a utility method that converts all regex matches to an ArrayList as given below.

Output

As you can see from the output, our pattern “\\d+” matched with all the numbers in a string that is then converted to the List by iterating over all the matches one by one.

If you are using Java version 9 or above, you can use the results method of the Matcher class that returns a Stream of MatchResult objects. You can then convert that stream to an array or a List object as given below.

Output

Please note that you need Java version 9 or above for this code to work.

If you want to learn more about regular expression in Java, please visit the Java regex tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.