Retrieve Matches Using Regular Expressions in Java
Obtaining an array of matches from a given string using regular expressions in Java involves creating a matcher and iterating over matches.
Using a Matcher
Create a Matcher object using the compile method of the Pattern class:
Matcher m = Pattern.compile("regex_expression").matcher(input_string);
Iterating over Matches
Use the find method of the Matcher to iterate over matches:
List<String> allMatches = new ArrayList<>(); while (m.find()) { allMatches.add(m.group()); }
Converting to Array
If you need an array of matches, use the toArray method:
String[] matchesArray = allMatches.toArray(new String[0]);
Enhanced Methods with MatchResult (Java >= 9)
In Java 9 and above, you can use the toMatchResult method on a Matcher to create a MatchResult object. This provides methods to create lazy iterators for efficient looping over matches:
for (MatchResult match : MatchResult.findAll(p, input)) { // Use match information without advancing iteration... }
For example, this code uses the allMatches helper method to iterate over matches, printing their groups and positions:
for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) { System.out.println(match.group() + " at " + match.start()); }
The above is the detailed content of How to Retrieve and Array of Matches from a String Using Java Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!