Home >Java >javaTutorial >How to Retrieve and Array of Matches from a String Using Java Regular Expressions?

How to Retrieve and Array of Matches from a String Using Java Regular Expressions?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 11:59:12202browse

How to Retrieve and Array of Matches from a String Using Java Regular Expressions?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn