MatchCollection.Item[Int32] 屬性

定義

取得集合的個別成員。

public:
 virtual property System::Text::RegularExpressions::Match ^ default[int] { System::Text::RegularExpressions::Match ^ get(int i); };
public virtual System.Text.RegularExpressions.Match this[int i] { get; }
member this.Item(int) : System.Text.RegularExpressions.Match
Default Public Overridable ReadOnly Property Item(i As Integer) As Match

參數

i
Int32

Match 集合內的索引。

屬性值

Match

在集合中位置 i 上的擷取的子字串。

實作

例外狀況

i 小於 0,或大於等於 Count

發生逾時。

範例

下列範例會剖析 Nathaniel Hawthorne 之 Seven Gables 的 House 的第一個 MatchCollection 句子,並傳回物件,其中包含以大寫或小寫 「h」 開頭的所有單字。 然後,屬性 Item[] 會用來擷取每個單字,並將其顯示至主控台。

using System;
using System.Text.RegularExpressions;

public class Class1
{
   public static void Main()
   {   
      string sentence = "Half-way down a by-street of one of our New England towns, stands a rusty wooden " +
                         "house, with seven acutely peaked gables, facing towards various points of the compass, " + 
                         "and a huge, clustered chimney in the midst.";
      string pattern = @"\b[hH]\w*\b"; 
      MatchCollection matches = Regex.Matches(sentence, pattern);
      for (int ctr=0; ctr < matches.Count; ctr++)
      {
         Console.WriteLine(matches[ctr].Value);   
      }   
   }
}
Option Strict On

Imports System.Text.RegularExpressions

Module TestMatches
   Public Sub Main()
      Dim pattern As String = "\b[hH]\w*\b"
      Dim sentence As String
      sentence = "Half-way down a by-street of one of our New England towns, stands a rusty wooden " & _
                 "house, with seven acutely peaked gables, facing towards various points of the compass, " & _ 
                 "and a huge, clustered chimney in the midst."
      Dim matches As MatchCollection = Regex.Matches(sentence, pattern)
      For ctr As Integer = 0 To Matches.Count - 1
         Console.WriteLine(matches.Item(ctr).Value)
      Next           
   End Sub
End Module

這個範例會產生下列輸出:

Half  
house  
huge  

備註

在 C# 中 Item[] ,屬性是索引子;它不會在程式碼中明確參考,而是允許 MatchCollection 存取集合,就像是陣列一樣。

一般而言,物件中的 MatchCollection 個別專案只有在集合中的專案總數從 Count 屬性決定之後,才會由其索引存取。 不過,存取 Count 屬性會導致正則運算式引擎使用直接評估一次全部建置集合。 這通常比使用 GetEnumerator 方法、C# foreach 語句或 Visual Basic For Each ... Next 語句來反覆運算集合更昂貴。

MatchCollection因為物件通常會使用延遲評估來填入,所以嘗試巡覽至特定相符專案可能會擲回 RegexMatchTimeoutException 例外狀況。 如果相符作業的逾時值生效,而且嘗試尋找特定相符專案超過該逾時間隔,就會擲回這個例外狀況。

適用於

另請參閱