O'Reilly logo

Regular Expressions Cookbook, 2nd Edition by Steven Levithan, Jan Goyvaerts

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.10. Retrieve a List of All Matches

Problem

All the preceding recipes in this chapter deal only with the first match that a regular expression can find in the subject string. But in many cases, a regular expression that partially matches a string can find another match in the remainder of the string. And there may be a third match after the second, and so on. For example, the regex \d+ can find six matches in the subject string The lucky numbers are 7, 13, 16, 42, 65, and 99: 7, 13, 16, 42, 65, and 99.

You want to retrieve the list of all substrings that the regular expression finds when it is applied repeatedly to the remainder of the string, after each match.

Solution

C#

You can use the static call when you process only a small number of strings with the same regular expression:

MatchCollection matchlist = Regex.Matches(subjectString, @"\d+");

Construct a Regex object if you want to use the same regular expression with a large number of strings:

Regex regexObj = new Regex(@"\d+");
MatchCollection matchlist = regexObj.Matches(subjectString);

VB.NET

You can use the static call when you process only a small number of strings with the same regular expression:

Dim MatchList = Regex.Matches(SubjectString, "\d+")

Construct a Regex object if you want to use the same regular expression with a large number of strings:

Dim RegexObj As New Regex("\d+")
Dim MatchList = RegexObj.Matches(SubjectString)

Java

List<String> resultList = new ArrayList<String>(); Pattern regex = Pattern.compile("\\d+"); Matcher ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required