Regex.Matches
This function uses a pattern argument. It searches the source String
to find all matches to that pattern. It returns Match
objects as part of a MatchCollection
.
Regex.Matches
is useful for complex text processing. It can be used instead of Match()
when more than one match is expected.
This program imports the System.Text.RegularExpressions
namespace. In Main
, we use the Regex.Matches
method on a String
literal containing several words starting with "s".
Regex
specifies that a match must start with s, have one or more non-whitespace characters, and end in d.Regex.Matches
function returns a MatchCollection
. We use the For-Each
looping construct on it (matches).Index
and Value from each Capture.Index
(the character position of the capture in the source string
) and a Value (the matching substring itself).Imports System.Text.RegularExpressions Module Module1 Sub Main() ' Input string. Dim value As String = "said shed see spear spread super" ' Call Regex.Matches method. Dim matches As MatchCollection = Regex.Matches(value, "s\w+d") ' Loop over matches. For Each m As Match In matches ' Loop over captures. For Each c As Capture In m.Captures ' Display. Console.WriteLine("Index={0}, Value={1}", c.Index, c.Value) Next Next End Sub End ModuleIndex=0, Value=said Index=5, Value=shed Index=20, Value=spread
Regex.Match
The Regex.Matches
function is basically the same as the Regex.Match
function except that it returns all matches rather than just the first one.
Regex.Matches
is the best function to choose.With Regex.Matches
, you can find all the matching parts in a source string
with a regular expression pattern. You need to then loop over all the individual matches.