MatchCollection.Count Property


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Gets the number of matches.

Namespace:   System.Text.RegularExpressions
Assembly:  System (in System.dll)

public int Count { get; }

Property Value

Type: System.Int32

The number of matches.

Exception Condition

A time-out occurred.

Accessing individual members of the MatchCollection object by retrieving the value of the collection's Count property causes the regular expression engine to populate the collection using direct evaluation. ln contrast, calling the GetEnumerator method (or using the foreach statement in C# and the For Each...Next statement in Visual Basic) causes the regular expression engine to populate the collection on an as needed basis using lazy evaluation. Direct evaluation can be a much more expensive method of building the collection than lazy evaluation.

Because the MatchCollection object is generally populated by using lazy evaluation, trying to determine the number of elements in the collection before it has been fully populated may throw a RegexMatchTimeoutException exception. This exception can be thrown if a time-out value for matching operations is in effect, and the attempt to find a single match exceeds that time-out interval.

The following example uses the Count property to determine whether the call to the Regex.Matches(String, String) method found any matches. If not, it indicates that no matches were found. Otherwise, it enumerates the matches and displays their value and the position in the input string at which they were found.

using System;
using System.Text.RegularExpressions;

public class Example
   public static void Main()
      string pattern = @"\d+";
      string[] inputs = { "This sentence contains no numbers.",
                          "123 What do I see?",
                          "2468 369 48 5" };
      foreach (var input in inputs) {
         MatchCollection matches = Regex.Matches(input, pattern);
         Console.WriteLine("Input: {0}", input);
         if (matches.Count == 0)
            Console.WriteLine("   No matches");
            foreach (Match m in matches)
               Console.WriteLine("   {0} at index {1}", m.Value, m.Index);

// The example displays the following output:
//       Input: This sentence contains no numbers.
//          No matches
//       Input: 123 What do I see?
//          123 at index 0
//       Input: 2468 369 48 5
//          2468 at index 0
//          369 at index 5
//          48 at index 9
//          5 at index 12

The regular expression pattern \d+ matches one or more decimal characters in an input string.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top