Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-11-24 11:59:12
Original
108 people have browsed it

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);
Copy after login

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());
}
Copy after login

Converting to Array

If you need an array of matches, use the toArray method:

String[] matchesArray = allMatches.toArray(new String[0]);
Copy after login

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...
}
Copy after login

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());
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template