Find All Occurrences of a Pattern in a String

Problem

You want to find every time a certain pattern occurs in a string and retrieve the corresponding text.

Solution

Use the Regex.Matches method to retrieve a collection with all the matches in a string.

Discussion

The System.Text.RegularExpressions namespace defines two classes that are used with matches. The Match class represents a single match and contains information such as the position in the string where the match was found, the length, and the text of the match. The MatchCollection class is a collection of Match instances. You can retrieve a MatchCollection that contains all the matches for a specific regular expression by calling Regex.Matches and supplying the search text.

The following example ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.