Beruflich Dokumente
Kultur Dokumente
net REGEX
The MatchCollection and Match Objects
Regex methods return two objects that are part of the regular expression object model: the MatchCollection object, and the
Match object.
The Regex.Matches method returns a MatchCollection object that contains Match objects that represent all the matches that
the regular expression engine found, in the order in which they occur in the input string. If there are no matches, the method
returns a MatchCollection object with no members. The MatchCollection.Item property lets you access individual members of
the collection by index, from zero to one less than the value of the MatchCollection.Count property. Item is the collection's
indexer (in C#) and default property (in Visual Basic).
By default, the call to the Regex.Matches method uses lazy evaluation to populate the MatchCollection object. Access to
properties that require a fully populated collection, such as the MatchCollection.Count and MatchCollection.Item properties,
may involve a performance penalty. As a result, we recommend that you access the collection by using the IEnumerator
object that is returned by the MatchCollection.GetEnumerator method. Individual languages provide constructs, such as For
Each in Visual Basic and foreach in C#, that wrap the collection's IEnumerator interface.
The following example uses the Regex.Matches(String) method to populate a MatchCollection object with all the matches
found in an input string. The example enumerates the collection, copies the matches to a string array, and records the
character positions in an integer array.
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim matches As MatchCollection
Dim results As New List(Of String)
Dim matchposition As New List(Of Integer)
' Create a new Regex object and define the regular expression.
Dim r As New Regex("abc")
' Use the Matches method to find all matches in the input string.
matches = r.Matches("123abc4abcd")
' Enumerate the collection to retrieve all matches and positions.
For Each match As Match In matches
' Add the match string to the string array.
results.Add(match.Value)
' Record the character position where the match was found.
matchposition.Add(match.Index)
Next
' List the results.
For ctr As Integer = 0 To results.Count - 1
Console.WriteLine("'{0}' found at position {1}.", _
results(ctr), matchposition(ctr))
Next
End Sub
End Module
' The example displays the following output:
' 'abc' found at position 3.
' 'abc' found at position 7.
The Match
The Match class represents the result of a single regular expression match. You can access Match objects in two ways:
By retrieving them from the MatchCollection object that is returned by the Regex.Matches method. To retrieve
individual Match objects, iterate the collection by using a foreach (in C#) or For Each...Next (in Visual Basic) construct,
or use the MatchCollectionItem property to retrieve a specific Match object either by index or by name. You can also
retrieve individual Match objects from the collection by iterating the collection by index, from zero to one less that the
number of objects in the collection. However, this method does not take advantage of lazy evaluation, because it
accesses the MatchCollection.Count property.
The following example retrieves individual Match objects from a MatchCollection object by iterating the collection
using the foreach or For Each...Next construct. The regular expression simply matches the string "abc" in the input
string.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "abc"
Dim input As String = "abc123abc456abc789"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("{0} found at position {1}.", _
match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
' abc found at position 0.
' abc found at position 6.
' abc found at position 12.
By calling the Regex.Match method, which returns a Match object that represents the first match in a string or a
portion of a string. You can determine whether the match has been found by retrieving the value of the
Match.Success property. To retrieve Match objects that represent subsequent matches, call the Match.NextMatch
method repeatedly, until the Success property of the returned Match object is false.
The following example uses the Regex.Match(String, String) and Match.NextMatch methods to match the string "abc" in
the input string.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "abc"
Dim input As String = "abc123abc456abc789"
Dim match As Match = Regex.Match(input, pattern)
Do While match.Success
Console.WriteLine("{0} found at position {1}.", _
match.Value, match.Index)
match = match.NextMatch()
Loop
End Sub
End Module
' The example displays the following output:
' abc found at position 0.
' abc found at position 6.
' abc found at position 12.
The Match.Groups property returns a GroupCollection object that contains information about the substrings that
match capturing groups in the regular expression pattern.
The Group.Captures property returns a CaptureCollection object that is of limited use. The collection is not populated
for a Match object whose Success property is false. Otherwise, it contains a single Capture object that has the same
information as the Match object.
For more information about these objects, see the The Group Collection and The Capture Collection sections later in this topic.
Two additional properties of the Match class provide information about the match. The Match.Value property returns the
substring in the input string that matches the regular expression pattern. The Match.Index property returns the zero-based
starting position of the matched string in the input string.
The Match.NextMatch method finds the match after the match represented by the current Match object, and returns a
Match object that represents that match.
The Match.Result method performs a specified replacement operation on the matched string and returns the result.
The following example uses the Match.Result method to prepend a $ symbol and a space before every number that includes
two fractional digits.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\d+(,\d{3})*\.\d{2}\b"
Dim input As String = "16.32" + vbCrLf + "194.03" + vbCrLf + "1,903,672.08"
The regular expression pattern \b\d+(,\d{3})*\.\d{2}\b is defined as shown in the following table.
Pattern Description
\b Begin the match at a word boundary.
(,\d{3})* Match zero or more occurrences of a comma followed by three decimal digits.
The replacement pattern $$ $& indicates that the matched substring should be replaced by a dollar sign ($) symbol (the $$
pattern), a space, and the value of the match (the $& pattern).
You can retrieve individual Group objects in the collection by using the GroupCollection.Item property. You can retrieve
unnamed groups by their ordinal position in the collection, and retrieve named groups either by name or by ordinal position.
Unnamed captures appear first in the collection, and are indexed from left to right in the order in which they appear in the
regular expression pattern. Named captures are indexed after unnamed captures, from left to right in the order in which they
appear in the regular expression pattern.
The GroupCollection.Item property is the indexer of the collection in C# and the collection object's default property in Visual
Basic. This means that individual Group objects can be accessed by index (or by name, in the case of named groups) as
follows:
The following example defines a regular expression that uses grouping constructs to capture the month, day, and year of a
date.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\w+)\s(\d{1,2}),\s(\d{4})\b"
Dim input As String = "Born: July 28, 1989"
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
For ctr As Integer = 0 To match.Groups.Count - 1
Console.WriteLine("Group {0}: {1}", ctr, match.Groups(ctr).Value)
Next
End If
End Sub
End Module
' The example displays the following output:
' Group 0: July 28, 1989
' Group 1: July
' Group 2: 28
' Group 3: 1989
The regular expression pattern \b(\w+)\s(\d{1,2}),\s(\d{4})\b is defined as shown in the following table.
Pattern Description
\b Begin the match at a word boundary.
(\w+) Match one or more word characters. This is the first capturing group.
\s Match a white-space character.
(\d{1,2}) Match one or two decimal digits. This is the second capturing group.
, Match a comma.
\s Match a white-space character.
(\d{4}) Match four decimal digits. This is the third capturing group.
\b End the match on a word boundary.
The following example uses nested grouping constructs to capture substrings into groups. The regular expression pattern
(a(b))c matches the string "abc". It assigns the substring "ab" to the first capturing group, and the substring "b" to the second
capturing group.
The following example uses named grouping constructs to capture substrings from a string that contains data in the format
"DATANAME:VALUE", which the regular expression splits at the colon (:).
The regular expression pattern ^(?<name>\w+):(?<value>\w+) is defined as shown in the following table.
Pattern Description
^ Begin the match at the beginning of the input string.
(?<name>\w+) Match one or more word characters. The name of this capturing group is name.
: Match a colon.
(?<value>\w+) Match one or more word characters. The name of this capturing group is value.
The properties of the Group class provide information about the captured group: The Group.Value property contains the
captured substring, the Group.Index property indicates the starting position of the captured group in the input text, the
Group.Length property contains the length of the captured text, and the Group.Success property indicates whether a
substring matched the pattern defined by the capturing group.
Applying quantifiers to a group (for more information, see Quantifiers) modifies the relationship of one capture per capturing
group in two ways:
If the * or *? quantifier (which specifies zero or more matches) is applied to a group, a capturing group may not
have a match in the input string. When there is no captured text, the properties of the Group object are set as shown
in the following table.
Value String.Empty
Length 0
The following example provides an illustration. In the regular expression pattern aaa(bbb)*ccc, the first capturing group
(the substring "bbb") can be matched zero or more times. Because the input string "aaaccc" matches the pattern, the
capturing group does not have a match.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "aaa(bbb)*ccc"
Dim input As String = "aaaccc"
Dim match As Match = Regex.Match(input, pattern)
Console.WriteLine("Match value: {0}", match.Value)
If match.Groups(1).Success Then
Console.WriteLine("Group 1 value: {0}", match.Groups(1).Value)
Else
Console.WriteLine("The first capturing group has no match.")
End If
End Sub
End Module
' The example displays the following output:
' Match value: aaaccc
' The first capturing group has no match.
Quantifiers can match multiple occurrences of a pattern that is defined by a capturing group. In this case, the Value and
Length properties of a Group object contain information only about the last captured substring. For example, the
following regular expression matches a single sentence that ends in a period. It uses two grouping constructs: The first
captures individual words along with a white-space character; the second captures individual words. As the output from
the example shows, although the regular expression succeeds in capturing an entire sentence, the second capturing
group captures only the last word.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b((\w+)\s?)+\."
Dim input As String = "This is a sentence. This is another sentence."
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
Console.WriteLine("Match: " + match.Value)
Console.WriteLine("Group 2: " + match.Groups(2).Value)
End If
End Sub
End Module
' The example displays the following output:
' Match: This is a sentence.
' Group 2: sentence
By iterating through the collection using a construct such as foreach (in C#) or For Each (in Visual Basic).
By using the CaptureCollection.Item property to retrieve a specific object by index. The Item property is the
CaptureCollection object's default property (in Visual Basic) or indexer (in C#).
If a quantifier is not applied to a capturing group, the CaptureCollection object contains a single Capture object that is of little
interest, because it provides information about the same match as its Group object. If a quantifier is applied to a capturing
group, the CaptureCollection object contains all captures made by the capturing group, and the last member of the collection
represents the same capture as the Group object.
For example, if you use the regular expression pattern ((a(b))c)+ (where the + quantifier specifies one or more matches) to
capture matches from the string "abcabcabc", the CaptureCollection object for each Group
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "((a(b))c)+"
Dim input As STring = "abcabcabc"
The Capture class contains the results from a single subexpression capture. The Capture.Value property contains the matched
text, and the Capture.Index property indicates the zero-based position in the input string at which the matched substring
begins.
The following example parses an input string for the temperature of selected cities. A comma (",") is used to separate a city
and its temperature, and a semicolon (";") is used to separate each city's data. The entire input string represents a single
match. In the regular expression pattern ((\w+(\s\w+)*),(\d+);)+, which is used to parse the string, the city name is assigned
to the second capturing group, and the temperature is assigned to the fourth capturing group.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;"
Dim pattern As String = "((\w+(\s\w+)*),(\d+);)+"
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
Console.WriteLine("Current temperatures:")
For ctr As Integer = 0 To match.Groups(2).Captures.Count - 1
Console.WriteLine("{0,-20} {1,3}", match.Groups(2).Captures(ctr).Value, _
match.Groups(4).Captures(ctr).Value)
Next
End If
End Sub
End Module
' The example displays the following output:
' Current temperatures:
' Miami 78
' Chicago 62
' New York 67
' San Francisco 59
Pattern Description
\w+ Match one or more word characters.
(\s\w+)* Match zero or more occurrences of a white-space character followed by one or more word
characters. This pattern matches multi-word city names. This is the third capturing group.
(\w+(\s\w+)*) Match one or more word characters followed by zero or more occurrences of a white-space
character and one or more word characters. This is the second capturing group.
, Match a comma.
(\d+) Match one or more digits. This is the fourth capturing group.
; Match a semicolon.
((\w+(\s\w+)*),(\d+);) Match the pattern of a word followed by any additional words followed by a comma, one or more
digits, and a semicolon, one or more times. This is the first capturing group.
+
MatchCollection Class
The MatchCollection type exposes the following members.
Properties
Name Description
Count Gets the number of matches.
IsReadOnly Gets a value that indicates whether the collection is read only.
IsSynchronized Gets a value indicating whether access to the collection is synchronized (thread-safe).
SyncRoot Gets an object that can be used to synchronize access to the collection.
Top
Methods
Name Description
CopyTo Copies all the elements of the collection to the given array starting at the given index.
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from
Object.)
Finalize Allows an object to try to free resources and perform other cleanup operations before it is
reclaimed by garbage collection. (Inherited from Object.)
GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
GetType Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClon Creates a shallow copy of the current Object. (Inherited from Object.)
e
ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Extension Methods
Name Description
AsParallel Enables parallelization of a query. (Defined by ParallelEnumerable.)
Cast(Of TResult) Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
OfType(Of TResult) Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top
Explicit Interface Implementations
Name Description
ICollection.CopyTo
ICollection.IsSynchronized
ICollection.SyncRoot
Top
Remarks
The collection is immutable (read-only) and has no public constructor. The Regex.Matches method returns a MatchCollection
object.
The collection contains zero or more System.Text.RegularExpressions.Match objects. If the match is successful, the collection is
populated with one System.Text.RegularExpressions.Match object for each match found in the input string. If the match is
unsuccessful, the collection contains no System.Text.RegularExpressions.Match objects, and its Count property equals zero.
When applying a regular expression pattern to a particular input string, the regular expression engine uses either of two
techniques to build the MatchCollection object:
Direct evaluation.
The MatchCollection object is populated all at once, with all matches resulting from a particular call to the
Regex.Matches method. This technique is used when the collection's Count property is accessed. It typically is the more
expensive method of populating the collection and entails a greater performance hit.
Lazy evaluation.
The MatchCollection object is populated as needed on a match-by-match basis. It is equivalent to the regular
expression engine calling the Regex.Match method repeatedly and adding each match to the collection. This
technique is used when the collection is accessed through its GetEnumerator method, or when it is accessed using the
foreach statement (in C#) or the For Each...Next statement (in Visual Basic).
To iterate through the members of the collection, you should use the collection iteration construct provided by your
language (such as foreach in C# and For Each…Next in Visual Basic) instead of retrieving the enumerator that is returned by
the GetEnumerator method.
Examples
The following example illustrates the use of the MatchCollection class to interrogate a set of Match instances.
Imports System
Imports System.Text.RegularExpressions
Properties
Name Description
Capture Gets a collection of all the captures matched by the capturing group, in innermost-leftmost-first
s order (or innermost-rightmost-first order if the regular expression is modified with the
RegexOptions.RightToLeft option). The collection may have zero or more items. (Inherited from
Group.)
Empty Gets the empty group. All failed matches return this empty match.
Index The position in the original string where the first character of the captured substring was found.
(Inherited from Capture.)
Success Gets a value indicating whether the match is successful. (Inherited from Group.)
Value Gets the captured substring from the input string. (Inherited from Capture.)
Methods
Name Description
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from
Object.)
Finalize Allows an object to try to free resources and perform other cleanup operations before it is
reclaimed by garbage collection. (Inherited from Object.)
GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
GetType Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClon Creates a shallow copy of the current Object. (Inherited from Object.)
e
NextMatch Returns a new Match object with the results for the next match, starting at the position at
which the last match ended (at the character after the last matched character).
Synchronized Returns a Match instance equivalent to the one supplied that is suitable to share between
multiple threads.
ToString Gets the captured substring from the input string. (Inherited from Capture.)
Remarks
The Match object is immutable and has no public constructor. An instance of the Match class is returned by the Regex.Match
method and represents the first pattern match in a string. Subsequent matches are represented by Match objects returned
by the Match.NextMatch method. In addition, a MatchCollection object that consists of zero, one, or more Match objects is
returned by the Regex.Matches method.
If the Regex.Matches method fails to match a regular expression pattern in an input string, it returns an empty MatchCollection
object. You can then use a foreach construct in C# or a For Each construct in Visual Basic to iterate the collection.
If the Regex.Match method fails to match the regular expression pattern, it returns a Match object that is equal to
Match.Empty. You can use the Success property to determine whether the match was successful. The following example
provides an illustration.
' Search for a pattern that is not found in the input string.
Dim pattern As String = "dog"
Dim input As String = "The cat saw the other cats playing in the back yard."
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
' Report position as a one-based integer.
Console.WriteLine("'{0}' was found at position {1} in '{2}'.", _
match.Value, match.Index + 1, input)
Else
Console.WriteLine("The pattern '{0}' was not found in '{1}'.", _
pattern, input)
End If
If a pattern match is successful, the Value property contains the matched substring, the Index property indicates the zero-
based starting position of the matched substring in the input string, and the Length property indicates the length of matched
substring in the input string.
Because a single match can involve multiple capturing groups, Match has a Groups property that returns the GroupCollection.
The GroupCollection has accessors that return each group. Match inherits from Group so the entire substring matched can be
accessed directly. That is, the Match instance itself is equivalent to Match.Groups[0] (Match.Groups(0) in Visual Basic).
Examples
The following examples use the regular expression Console.Write(Line)?. The regular expression is interpreted as follows:
Example 1
The following example calls the Regex.Matches(String, String) method to retrieve all pattern matches in an input string. It then
iterates the Match objects in the returned MatchCollection object to display information about each match.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "Dim values() As Integer = { 1, 2, 3 }" & vbCrLf & _
"For ctr As Integer = values.GetLowerBound(1) To
values.GetUpperBound(1)" & vbCrLf & _
" Console.Write(values(ctr))" & vbCrLf & _
" If ctr < values.GetUpperBound(1) Then Console.Write("", "")" &
vbCrLf & _
"Next" & vbCrLf & _
"Console.WriteLine()"
Dim pattern As String = "Console.Write(Line)?"
Dim matches As MatchCollection = Regex.Matches(input, pattern)
For Each match As Match In matches
Console.WriteLine("'{0}' found in the source code at position {1}.", _
match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
' 'Console.Write' found in the source code at position 115.
' 'Console.Write' found in the source code at position 184.
' 'Console.WriteLine' found in the source code at position 211.
Example 2
The following example calls the Match(String, String) and NextMatch methods to retrieve one match at a time.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "Dim values() As Integer = { 1, 2, 3 }" & vbCrLf & _
"For ctr As Integer = values.GetLowerBound(1) To
values.GetUpperBound(1)" & vbCrLf & _
" Console.Write(values(ctr))" & vbCrLf & _
" If ctr < values.GetUpperBound(1) Then Console.Write("", "")" &
vbCrLf & _
"Next" & vbCrLf & _
"Console.WriteLine()"
Dim pattern As String = "Console.Write(Line)?"
Dim match As Match = Regex.Match(input, pattern)
Do While match.Success
Console.WriteLine("'{0}' found in the source code at position {1}.", _
match.Value, match.Index)
match = match.NextMatch()
Loop
End Sub
End Module
' The example displays the following output:
' 'Console.Write' found in the source code at position 115.
' 'Console.Write' found in the source code at position 184.
' 'Console.WriteLine' found in the source code at position 211.
GroupCollection Class
The GroupCollection type exposes the following members.
Properties
Name Description
Count Returns the number of groups in the collection.
IsSynchronize Gets a value that indicates whether access to the GroupCollection is synchronized (thread-
d safe).
SyncRoot Gets an object that can be used to synchronize access to the GroupCollection.
Methods
Name Description
CopyTo Copies all the elements of the collection to the given array beginning at the given index.
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from
Object.)
Finalize Allows an object to try to free resources and perform other cleanup operations before it is
reclaimed by garbage collection. (Inherited from Object.)
GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
GetType Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClon Creates a shallow copy of the current Object. (Inherited from Object.)
e
ToString Returns a string that represents the current object. (Inherited from Object.)
Extension Methods
Name Description
AsParallel Enables parallelization of a query. (Defined by ParallelEnumerable.)
Cast(Of TResult) Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
OfType(Of TResult) Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Explicit Interface Implementations
Name Description
ICollection.CopyTo
ICollection.IsSynchronized
ICollection.SyncRoot
Remarks
The collection is immutable (read-only) and has no public constructor. A GroupCollection object is returned by the
Match.Groups property.
The collection contains one or more System.Text.RegularExpressions.Group objects. If the match is successful, the first element
in the collection contains the Group object that corresponds to the entire match. Each subsequent element represents a
captured group, if the regular expression includes capturing groups. If the match is unsuccessful, the collection contains a
single System.Text.RegularExpressions.Group object whose Success property is false and whose Value property equals
String.Empty.
To iterate through the members of the collection, you should use the collection iteration construct provided by your
language (such as foreach in C# and For Each…Next in Visual Basic) instead of retrieving the enumerator that is returned by
the GetEnumerator method.
Examples
The following example uses a regular expression with capturing groups to extract information about trademarks and
registered trademarks used in text. The regular expression pattern is \b(\w+?)([\u00AE\u2122]), which is interpreted as shown
in the following table.
Pattern Description
\b Look for a word boundary.
(\w+?) Look for one or more word characters. Together, these form the trademarked name. (Note that this
regular expression assumes that a trademark consists of a single word.) This is the first capturing group.
([\u00AE\u2122] Look for either the ® or the ™ character. This is the second capturing group.
)
For each match, the GroupCollection contains three Group objects. The first object contains the string that matches the entire
regular expression. The second object, which represents the first captured group, contains the product name. The third
object, which represents the second captured group, contains the trademark or registered trademark symbol.
Module Example
Public Sub Main()
Dim pattern As String = "\b(\w+?)([\u00AE\u2122])"
Dim input As String = "Microsoft® Office Professional Edition combines several office " +
_
"productivity products, including Word, Excel®, Access®, Outlook®,
" + _
"PowerPoint®, and several others. Some guidelines for creating " +
_
"corporate documents using these productivity tools are available "
+ _
"from the documents created using Silverlight™ on the corporate " +
_
"intranet site."
Dim matches As MatchCollection = Regex.Matches(input, pattern)
For Each match As Match In matches
Dim groups As GroupCollection = match.Groups
Console.WriteLine("{0}: {1}", groups(2), groups(1))
Next
Console.WriteLine()
Console.WriteLine("Found {0} trademarks or registered trademarks.", matches.Count)
End Sub
End Module
' The example displays the following output:
' r: Microsoft
' r: Excel
' r: Access
' r: Outlook
' r: PowerPoint
' T: Silverlight
GroupCollection Class
Returns the set of captured groups in a single match.
Properties
Name Description
Count Returns the number of groups in the collection.
IsSynchronize Gets a value that indicates whether access to the GroupCollection is synchronized (thread-
d safe).
SyncRoot Gets an object that can be used to synchronize access to the GroupCollection.
Methods
Name Description
CopyTo Copies all the elements of the collection to the given array beginning at the given index.
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited)
Finalize Allows an object to try to free resources and perform other cleanup operations before it is
reclaimed by garbage collection. (Inherited from Object.)
GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
GetType Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClon Creates a shallow copy of the current Object. (Inherited from Object.)
e
ToString Returns a string that represents the current object. (Inherited from Object.)
Extension Methods
Name Description
AsParallel Enables parallelization of a query. (Defined by ParallelEnumerable.)
Cast(Of TResult) Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
OfType(Of TResult) Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Explicit Interface Implementations
Name Description
ICollection.CopyTo
ICollection.IsSynchronized
ICollection.SyncRoot
Remarks
The collection is immutable (read-only) and has no public constructor. A GroupCollection object is returned by the
Match.Groups property.
The collection contains one or more System.Text.RegularExpressions.Group objects. If the match is successful, the first element
in the collection contains the Group object that corresponds to the entire match. Each subsequent element represents a
captured group, if the regular expression includes capturing groups. If the match is unsuccessful, the collection contains a
single System.Text.RegularExpressions.Group object whose Success property is false and whose Value property equals
String.Empty.
To iterate through the members of the collection, you should use the collection iteration construct provided by your
language (such as foreach in C# and For Each…Next in Visual Basic) instead of retrieving the enumerator that is returned by
the GetEnumerator method.
Examples
The following example uses a regular expression with capturing groups to extract information about trademarks and
registered trademarks used in text. The regular expression pattern is \b(\w+?)([\u00AE\u2122]), which is interpreted as shown
in the following table.
Pattern Description
\b Look for a word boundary.
(\w+?) Look for one or more word characters. Together, these form the trademarked name. (Note that this
regular expression assumes that a trademark consists of a single word.) This is the first capturing group.
([\u00AE\u2122] Look for either the ® or the ™ character. This is the second capturing group.
)
For each match, the GroupCollection contains three Group objects. The first object contains the string that matches the entire
regular expression. The second object, which represents the first captured group, contains the product name. The third
object, which represents the second captured group, contains the trademark or registered trademark symbol.
Module Example
Public Sub Main()
Dim pattern As String = "\b(\w+?)([\u00AE\u2122])"
Dim input As String = "Microsoft® Office Professional Edition combines several office " +
_
"productivity products, including Word, Excel®, Access®, Outlook®,
" + _
"PowerPoint®, and several others. Some guidelines for creating " +
_
"corporate documents using these productivity tools are available "
+ _
"from the documents created using Silverlight™ on the corporate " +
_
"intranet site."
Properties
Name Description
Index The position in the original string where the first character of the captured substring was found.
Methods
Name Description
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from
Object.)
Finalize Allows an object to try to free resources and perform other cleanup operations before it is
reclaimed by garbage collection. (Inherited from Object.)
GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
GetType Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClon Creates a shallow copy of the current Object. (Inherited from Object.)
e
ToString Gets the captured substring from the input string. (Overrides Object.ToString.)
Remarks
A Capture object is immutable and has no public constructor. Instances are returned through the CaptureCollection object,
which is returned by the Match.Captures and Group.Captures properties. However, the Match.Captures property provides
information about the same match as the Match object.
If you do not apply a quantifier to a capturing group, the Group.Captures property returns a CaptureCollection with a single
Capture object that provides information about the same capture as the Group object. If you do apply a quantifier to a
capturing group, the Group.Index, Group.Length, and Group.Value properties provide information only about the last
captured group, whereas the Capture objects in the CaptureCollection provide information about all subexpression captures.
The example provides an illustration.
Examples
The following example defines a regular expression that matches sentences that contain no punctuation except for a period
(".").
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "Yes. This dog is very friendly."
Dim pattern As String = "((\w+)[\s.])+"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("Match: {0}", match.Value)
For groupCtr As Integer = 0 To match.Groups.Count - 1
Dim group As Group = match.Groups(groupCtr)
Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value)
For captureCtr As Integer = 0 To group.Captures.Count - 1
Console.WriteLine(" Capture {0}: {1}", captureCtr, _
group.Captures(captureCtr).Value)
Next
Next
Next
End Sub
End Module
' The example displays the following output:
' Match: Yes.
' Group 0: Yes.
' Capture 0: Yes.
' Group 1: Yes.
' Capture 0: Yes.
' Group 2: Yes
' Capture 0: Yes
' Match: This dog is very friendly.
' Group 0: This dog is very friendly.
' Capture 0: This dog is very friendly.
' Group 1: friendly.
' Capture 0: This
' Capture 1: dog
' Capture 2: is
' Capture 3: very
' Capture 4: friendly.
' Group 2: friendly
' Capture 0: This
' Capture 1: dog
' Capture 2: is
' Capture 3: very
' Capture 4: friendly
The regular expression pattern ((\w+)[\s.])+ is defined as shown in the following table. Note that in this regular expression, a
quantifier is applied to the entire regular expression.
Pattern Description
(\w+) Match one or more word characters. This is the second capturing group.
((\w+)[\s.]) Match one or more word characters followed by a white-space character or period ("."). This is the first
capturing group.
((\w+)[\s.]) Match one or more occurrences of a word character or characters followed by a white-space character or
+ period (".").
In this example, the input string consists of two sentences. As the output shows, because the first sentence consists of only
one word, the CaptureCollection object has a single Capture object that represents the same capture as the Group object.
Because the second sentence consists of multiple words, the Group objects only contain information about the last matched
subexpression. Group 1, which represents the first capture, contains the last word in the sentence with a closing period.
Group 2, which represents the second capture, contains the last word in the sentence. However, the Capture objects in the
group's CaptureCollection object capture each subexpression match. The Capture objects in the first capturing group's
collection of captures contain information about each captured word and white-space character or period. The Capture
objects in the second capturing group's collection of captures contain information about each captured word.