Home > Java > javaTutorial > How Can I Extract All Regex Matches into an Array in Java?

How Can I Extract All Regex Matches into an Array in Java?

Linda Hamilton
Release: 2024-12-08 19:04:14
Original
1006 people have browsed it

How Can I Extract All Regex Matches into an Array in Java?

Extract String Matches into Array Using Regex Expressions in Java

In Java, the inability to directly obtain an array of regex matches may leave you puzzled. This guide addresses this challenge, providing solutions to capture all strings that conform to a regular expression.

The key to retrieving these matches lies in utilizing a matcher, which iteratively locates occurrences:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

List<String> allMatches = new ArrayList<>();
Matcher m = Pattern.compile("your regex expression here")
    .matcher(yourStringHere);
while (m.find()) {
   allMatches.add(m.group());
}
Copy after login

After populating allMatches with the matches, you can convert it to an array if necessary:

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

Alternatively, you may consider using MatchResult to simplify matching operations. A helper function like allMatches:

public static Iterable<MatchResult> allMatches(
      final Pattern p, final CharSequence input) {
  ...
}
Copy after login

allows you to iterate over matches, such as:

for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
  System.out.println(match.group() + " at " + match.start());
}
Copy after login

Providing the output:

a at 0
b at 1
a at 3
c at 4
a at 5
a at 7
b at 8
a at 10
Copy after login

The above is the detailed content of How Can I Extract All Regex Matches into an Array in Java?. 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