Retrieval of Array of Regex Matches in Java
Problem:
When using regex expressions in Java, the primary method for checking matches only returns a boolean value, indicating whether a match is present or not. This can be limiting when attempting to capture and store multiple matching instances in an array.
Solution:
To construct an array of all string matches found within a given string using a regex expression, follow these steps:
Example Code:
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.List; import java.util.ArrayList; public class RegexArray { public static void main(String[] args) { String input = "This is a sample string"; String regex = "[a-z]+"; // Create a Matcher object Matcher matcher = Pattern.compile(regex).matcher(input); // Collect matching substrings List<String> matches = new ArrayList<>(); while (matcher.find()) { matches.add(matcher.group()); } // Convert to string array String[] matchArray = matches.toArray(new String[0]); } }
By implementing these steps, you can effectively capture and store all instances that match a specified regex expression in an array, providing a structured and organized way to work with matched data.
The above is the detailed content of How Can I Retrieve an Array of Regex Matches in Java?. For more information, please follow other related articles on the PHP Chinese website!