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 use a regex match to form an array of all string matching a regex expression in a given string?
(4castle’s answer is better than the below if you can assume Java >= 9)
You need to create a matcher and use that to iteratively find matches.
After this,
allMatchescontains the matches, and you can useallMatches.toArray(new String[0])to get an array if you really need one.You can also use
MatchResultto write helper functions to loop over matchessince
Matcher.toMatchResult()returns a snapshot of the current group state.For example you can write a lazy iterator to let you do
by doing something like this:
With this,
yields