MatchCollection.Count 屬性

定義

取得符合項的數目。

public:
 property int Count { int get(); };
public int Count { get; }
member this.Count : int
Public ReadOnly Property Count As Integer

屬性值

符合項的數目。

實作

例外狀況

發生逾時。

範例

下列範例會 Count 使用 屬性來判斷方法的 Regex.Matches(String, String) 呼叫是否找到任何相符專案。 如果沒有,表示找不到相符專案。 否則,它會列舉相符專案,並顯示其值及其在輸入字串中找到的位置。

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");
         else
            foreach (Match m in matches)
               Console.WriteLine("   {0} at index {1}", m.Value, m.Index);

         Console.WriteLine();
      }
   }
}
// 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
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\d+"
      Dim inputs() As String = { "This sentence contains no numbers.",
                                 "123 What do I see?",
                                 "2468 369 48 5" }
      For Each inputStr In inputs
         Dim matches As MatchCollection = Regex.Matches(inputStr, pattern)
         Console.WriteLine("Input: {0}", inputStr)
         If matches.Count = 0
            Console.WriteLine("   No matches")
         Else
            For Each m As Match In matches
               Console.WriteLine("   {0} at index {1}", m.Value, m.Index)
            Next
         End If
         Console.WriteLine()
      Next
   End Sub
End Module
' 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

正則運算式模式 \d+ 會比對輸入字串中的一或多個十進位字元。

備註

藉由擷取集合的 Count 屬性值來存取物件的個別成員 MatchCollection ,會導致正則運算式引擎使用直接評估填入集合。 ln 對比,呼叫 GetEnumerator 方法 (或使用 foreach C# 中的 語句和 For Each Visual Basic 中的 ... Next 語句) 會導致正則運算式引擎視需要使用延遲評估來填入集合。 直接評估是建置集合比延遲評估更昂貴的方法。

MatchCollection因為物件通常會使用延遲評估來填入,所以嘗試在完全填入之前先判斷集合中的元素數目可能會擲回 RegexMatchTimeoutException 例外狀況。 如果比對作業的逾時值生效,而且嘗試尋找單一相符專案超過該逾時間隔,就會擲回這個例外狀況。

適用於