Regex.Match 方法

定義

在輸入字串搜尋規則運算式的項目,並傳回正確結果為單一 Match 物件。Searches an input string for a substring that matches a regular expression pattern and returns the first occurrence as a single Match object.

多載

Match(String, String, RegexOptions, TimeSpan)

使用指定的比對選項和逾時間隔,在輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.

Match(String, Int32, Int32)

從指定的開始位置開始並且僅搜尋指定數目的字元,在輸入字串中搜尋規則運算式的第一個相符項目。Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.

Match(String, String, RegexOptions)

使用指定的比對選項,在輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.

Match(String, Int32)

從字串中指定的開始位置開始,在輸入字串中搜尋規則運算式的第一個相符項目。Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

Match(String)

在指定的輸入字串中,搜尋符合 Regex 建構函式中所指定規則運算式的第一個項目。Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

Match(String, String)

在指定的輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the specified input string for the first occurrence of the specified regular expression.

Match(String, String, RegexOptions, TimeSpan)

使用指定的比對選項和逾時間隔,在輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.

public:
 static System::Text::RegularExpressions::Match ^ Match(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static System.Text.RegularExpressions.Match Match (string input, string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Match : string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.Match
Public Shared Function Match (input As String, pattern As String, options As RegexOptions, matchTimeout As TimeSpan) As Match

參數

input
String

用來搜尋比對的字串。The string to search for a match.

pattern
String

要比對的規則運算式模式。The regular expression pattern to match.

options
RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

matchTimeout
TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeoutA time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

傳回

物件,包含符合之項目的相關資訊。An object that contains information about the match.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

-或--or- matchTimeout 為負數、零或約大於 24 天。matchTimeout is negative, zero, or greater than approximately 24 days.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

Match(String, String, RegexOptions, TimeSpan)方法會傳回輸入字串中符合正則運算式模式的第一個子字串。The Match(String, String, RegexOptions, TimeSpan) method returns the first substring that matches a regular expression pattern in an input string. 如需用來建立正則運算式模式之語言元素的詳細資訊, 請參閱正則運算式語言-快速參考For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

靜態Match(String, String, RegexOptions, TimeSpan)方法相當於使用此Regex(String, RegexOptions, TimeSpan)函數來Regex建立物件, 並呼叫實例Match(String)方法。The static Match(String, String, RegexOptions, TimeSpan) method is equivalent to constructing a Regex object with the Regex(String, RegexOptions, TimeSpan) constructor and calling the instance Match(String) method.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

您可以藉由檢查傳回Match Success物件之屬性的值, 判斷是否在輸入字串中找到正則運算式模式。You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. 如果找到符合的項目,則所傳回 Match 物件的 Value 屬性會包含符合規則運算式模式之 input 的子字串。If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. 如果找不到相符的, 其值String.Empty為。If no match is found, its value is String.Empty.

這個方法會傳回中input找到的第一個子字串符合正則運算式模式。This method returns the first substring found in input that matches the regular expression pattern. 您可以藉由重複呼叫傳回Match的物件的NextMatch方法, 來抓取後續的相符專案。You can retrieve subsequent matches by repeatedly calling the returned Match object's NextMatch method. 您也可以藉由呼叫Regex.Matches(String, String, RegexOptions)方法, 在單一方法呼叫中取出所有相符專案。You can also retrieve all matches in a single method call by calling the Regex.Matches(String, String, RegexOptions) method.

matchTimeout參數會指定模式比對方法應該在超時之前嘗試尋找相符的時間長度。設定逾時間隔, 可防止依賴過量回溯的正則運算式在處理包含接近相符專案的輸入時停止回應。The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. 如需詳細資訊, 請參閱正則運算式和回溯的最佳做法For more information, see Best Practices for Regular Expressions and Backtracking. 如果在該時間間隔內找不到相符的結果, 則RegexMatchTimeoutException方法會擲回例外狀況。If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout針對方法執行所在的應用程式域, 覆寫任何定義的預設超時值。matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

給呼叫者的注意事項

我們建議您將matchTimeout參數設定為適當的值, 例如兩秒。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果您藉由指定InfiniteMatchTimeout來停用超時, 則正則運算式引擎可提供稍微較佳的效能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 不過, 只有在下列情況下, 您才應該停用超時:However, you should disable time-outs only under the following conditions: -當正則運算式所處理的輸入衍生自已知且受信任的來源, 或包含靜態文字時。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 這會排除使用者動態輸入的文字。This excludes text that has been dynamically input by users.

-當正則運算式模式經過徹底測試, 以確保它能有效率地處理相符、不相符和接近的相符專案。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-當正則運算式模式未包含任何已知在處理接近相符專案時造成過多回溯的語言元素時。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另請參閱

Match(String, Int32, Int32)

從指定的開始位置開始並且僅搜尋指定數目的字元,在輸入字串中搜尋規則運算式的第一個相符項目。Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.

public:
 System::Text::RegularExpressions::Match ^ Match(System::String ^ input, int beginning, int length);
public System.Text.RegularExpressions.Match Match (string input, int beginning, int length);
member this.Match : string * int * int -> System.Text.RegularExpressions.Match
Public Function Match (input As String, beginning As Integer, length As Integer) As Match

參數

input
String

用來搜尋比對的字串。The string to search for a match.

beginning
Int32

定義要搜尋的最左邊位置的輸入字串中以零為起始的字元位置。The zero-based character position in the input string that defines the leftmost position to be searched.

length
Int32

子字串中要包含在搜尋中的字元數。The number of characters in the substring to include in the search.

傳回

物件,包含符合之項目的相關資訊。An object that contains information about the match.

例外狀況

inputnullinput is null.

beginning 小於零或大於 input的長度。beginning is less than zero or greater than the length of input.

-或--or- length 小於零或大於 input 的長度。length is less than zero or greater than the length of input.

-或--or- beginning+length-1 識別 input 範圍之外的位置。beginning+length-1 identifies a position that is outside the range of input.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

Match(String, Int32, Int32)方法會傳回第一個符合正則運算式模式的子字串, 在輸入字串的某個部分中。The Match(String, Int32, Int32) method returns the first substring that matches a regular expression pattern in a portion of an input string. 如需用來建立正則運算式模式之語言元素的詳細資訊, 請參閱正則運算式語言-快速參考For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

Match(String, Int32, Int32)方法搜尋的正則運算式模式是由呼叫其中一個Regex類別的函式所定義。The regular expression pattern for which the Match(String, Int32, Int32) method searches is defined by the call to one of the Regex class constructors. 如需可形成正則運算式模式之元素的詳細資訊, 請參閱正則運算式語言-快速參考For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.

方法會在beginninginput 參數length所定義的部分中搜尋正則運算式模式。 Match(String, Int32, Int32)The Match(String, Int32, Int32) method searches the portion of input defined by the beginning and length parameters for the regular expression pattern. beginning一律會定義要包含在搜尋中最左邊字元的索引, 並length定義要搜尋的最大字元數。beginning always defines the index of the leftmost character to include in the search, and length defines the maximum number of characters to search. 它們會一起定義搜尋範圍。Together, they define the range of the search. 如果搜尋從左至右 (預設值) 進行, 正則運算式引擎會從beginning索引處的字元搜尋到位於索引beginning + length -1 的字元。If the search proceeds from left to right (the default), the regular expression engine searches from the character at index beginning to the character at index beginning + length - 1. 如果正則RegexOptions.RightToLeft運算式引擎是使用選項具現化, 讓搜尋從右至左進行, 正則運算式引擎會從位於索引beginning + length -1 的字元搜尋到索引beginning處的字元。If the regular expression engine was instantiated by using the RegexOptions.RightToLeft option so that the search proceeds from right to left, the regular expression engine searches from the character at index beginning + length - 1 to the character at index beginning. 這個方法會傳回它在此範圍內找到的第一個相符項。This method returns the first match that it finds within this range. 您可以藉由重複呼叫傳回Match的物件的Match.NextMatch方法, 來抓取後續的相符專案。You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method.

您可以藉由檢查傳回Match Success物件之屬性的值, 判斷是否在輸入字串中找到正則運算式模式。You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. 如果找到符合的項目,則所傳回 Match 物件的 Value 屬性會包含符合規則運算式模式之 input 的子字串。If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. 如果找不到相符的, 其值String.Empty為。If no match is found, its value is String.Empty.

如果比對作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 當您呼叫此函式時, 如果未設定超時值, 則如果作業超過針對建立Regex物件之應用程式域所建立的任何超時值, 就會擲回例外狀況。If you do not set a time-out value when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

另請參閱

Match(String, String, RegexOptions)

使用指定的比對選項,在輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.

public:
 static System::Text::RegularExpressions::Match ^ Match(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public static System.Text.RegularExpressions.Match Match (string input, string pattern, System.Text.RegularExpressions.RegexOptions options);
static member Match : string * string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.Match
Public Shared Function Match (input As String, pattern As String, options As RegexOptions) As Match

參數

input
String

用來搜尋比對的字串。The string to search for a match.

pattern
String

要比對的規則運算式模式。The regular expression pattern to match.

options
RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

傳回

物件,包含符合之項目的相關資訊。An object that contains information about the match.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會定義符合以字母 "a" 開頭之單字的正則運算式。The following example defines a regular expression that matches words beginning with the letter "a". 它會使用RegexOptions.IgnoreCase選項來確保正則運算式會尋找開頭為大寫 "a" 和小寫 "a" 的單字。It uses the RegexOptions.IgnoreCase option to ensure that the regular expression locates words beginning with both an uppercase "a" and a lowercase "a".

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\ba\w*\b";
      string input = "An extraordinary day dawns with each new day.";
      Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
      if (m.Success)
         Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index);
   }
}
// The example displays the following output:
//        Found 'An' at position 0.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\ba\w*\b"
      Dim input As String = "An extraordinary day dawns with each new day."
      Dim m As Match = Regex.Match(input, pattern, RegexOptions.IgnoreCase)
      If m.Success Then
         Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index)
      End If
   End Sub
End Module
' The example displays the following output:
'       Found 'An' at position 0.

規則運算式模式 \ba\w*\b 的解譯方式如下表所示。The regular expression pattern \ba\w*\b is interpreted as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
a 比對字元 "a"。Match the character "a".
\w* 比對零個、一個或多個文字字元。Match zero, one, or more word characters.
\b 結束字緣比對。End the match at a word boundary.

備註

Match(String, String, RegexOptions)方法會傳回輸入字串中符合正則運算式模式的第一個子字串。The Match(String, String, RegexOptions) method returns the first substring that matches a regular expression pattern in an input string. 如需用來建立正則運算式模式之語言元素的詳細資訊, 請參閱正則運算式語言-快速參考For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

靜態Match(String, String, RegexOptions)方法相當於使用此Regex(String, RegexOptions)函數來Regex建立物件, 並呼叫實例Match(String)方法。The static Match(String, String, RegexOptions) method is equivalent to constructing a Regex object with the Regex(String, RegexOptions) constructor and calling the instance Match(String) method.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

您可以藉由檢查傳回Match Success物件之屬性的值, 判斷是否在輸入字串中找到正則運算式模式。You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. 如果找到符合的項目,則所傳回 Match 物件的 Value 屬性會包含符合規則運算式模式之 input 的子字串。If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. 如果找不到相符的, 其值String.Empty為。If no match is found, its value is String.Empty.

這個方法會傳回中input找到的第一個子字串符合正則運算式模式。This method returns the first substring found in input that matches the regular expression pattern. 您可以藉由重複呼叫傳回Match的物件的NextMatch方法, 來抓取後續的相符專案。You can retrieve subsequent matches by repeatedly calling the returned Match object's NextMatch method. 您也可以藉由呼叫Regex.Matches(String, String, RegexOptions)方法, 在單一方法呼叫中取出所有相符專案。You can also retrieve all matches in a single method call by calling the Regex.Matches(String, String, RegexOptions) method.

如果比對作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 用來抓取模式比對的建議靜態方法Match(String, String)是, 可讓您設定逾時間隔。The recommended static method for retrieving a pattern match is Match(String, String), which lets you set the time-out interval.

另請參閱

Match(String, Int32)

從字串中指定的開始位置開始,在輸入字串中搜尋規則運算式的第一個相符項目。Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

public:
 System::Text::RegularExpressions::Match ^ Match(System::String ^ input, int startat);
public System.Text.RegularExpressions.Match Match (string input, int startat);
member this.Match : string * int -> System.Text.RegularExpressions.Match
Public Function Match (input As String, startat As Integer) As Match

參數

input
String

用來搜尋比對的字串。The string to search for a match.

startat
Int32

要開始搜尋之以零起始的字元位置。The zero-based character position at which to start the search.

傳回

物件,包含符合之項目的相關資訊。An object that contains information about the match.

例外狀況

inputnullinput is null.

startat 小於零或大於 input 的長度。startat is less than zero or greater than the length of input.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法會傳回第一個符合正則運算式模式的子字串, 在輸入字串中startat從字元位置開始或之後。 Match(String, Int32)The Match(String, Int32) method returns the first substring that matches a regular expression pattern, starting at or after the startat character position, in an input string. 如需用來建立正則運算式模式之語言元素的詳細資訊, 請參閱正則運算式語言-快速參考For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

Match(String, Int32)方法搜尋的正則運算式模式是由呼叫其中一個Regex類別的函式所定義。The regular expression pattern for which the Match(String, Int32) method searches is defined by the call to one of the Regex class constructors. 如需可形成正則運算式模式之元素的詳細資訊, 請參閱正則運算式語言-快速參考For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.

您可以使用startat參數, 選擇性地指定字串中的開始位置。You can optionally specify a starting position in the string by using the startat parameter. 當正則運算式引擎從左至右 (預設值) 進行剖析時, 會從中startat指定的字元開始, 符合和掃描移動向右。When the regular expression engine parses from left to right (the default), the match and the scan move rightward, starting at the character specified in startat. 當正則運算式引擎從右至左剖析時 (使用RegexOptions.RightToLeft選項來建立正則運算式模式時), 比對和掃描會以相反方向移動, 並以startat -1 的字元開頭。When the regular expression engine parses from right to left (when the regular expression pattern is constructed with the RegexOptions.RightToLeft option), the match and scan move in the opposite direction and begin with the character at startat -1. 如果您未指定開始位置, 則會從預設startat位置開始搜尋。If you do not specify a starting position, the search begins at the default startat position. 如果正則運算式會從左至右搜尋, 則startat預設位置為的左邊input, 如果是由右至左搜尋, 則預設startat位置會在的右邊inputIf the regular expression searches from left to right, the default startat position is at the left end of input; if it searches from right to left, the default startat position is at the right end of input.

如果您想要限制比對, 使其從字串中的特定字元位置開始, 而且正則運算式引擎不會掃描字串的其餘部分是否相符, 請將正則運算式\G錨定為 (從左至右的左邊)模式, 或從右至左模式的右邊。If you want to restrict a match so that it begins at a particular character position in the string and the regular expression engine does not scan the remainder of the string for a match, anchor the regular expression with a \G (at the left for a left-to-right pattern, or at the right for a right-to-left pattern). 這會限制比對, 使其必須完全startat從開始。This restricts the match so it must start exactly at startat.

您可以藉由檢查傳回Match Success物件之屬性的值, 判斷是否在輸入字串中找到正則運算式模式。You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. 如果找到符合的項目,則所傳回 Match 物件的 Value 屬性會包含符合規則運算式模式之 input 的子字串。If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. 如果找不到相符的, 其值String.Empty為。If no match is found, its value is String.Empty.

這個方法會傳回在中startat input符合正則運算式模式的字元位置或後面找到的第一個子字串。This method returns the first substring found at or after the startat character position in input that matches the regular expression pattern. 您可以藉由重複呼叫傳回Match的物件的Match.NextMatch方法, 來抓取後續的相符專案。You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. 您也可以藉由呼叫Regex.Matches(String, Int32)方法, 在單一方法呼叫中取出所有相符專案。You can also retrieve all matches in a single method call by calling the Regex.Matches(String, Int32) method.

如果比對作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

另請參閱

Match(String)

在指定的輸入字串中,搜尋符合 Regex 建構函式中所指定規則運算式的第一個項目。Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

public:
 System::Text::RegularExpressions::Match ^ Match(System::String ^ input);
public System.Text.RegularExpressions.Match Match (string input);
member this.Match : string -> System.Text.RegularExpressions.Match
Public Function Match (input As String) As Match

參數

input
String

用來搜尋比對的字串。The string to search for a match.

傳回

物件,包含符合之項目的相關資訊。An object that contains information about the match.

例外狀況

inputnullinput is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會在字串中尋找正則運算式模式比對, 然後列出相符的群組、捕獲和捕捉位置。The following example finds regular expression pattern matches in a string, then lists the matched groups, captures, and capture positions.

#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
void main()
{
   
   String^ text = "One car red car blue car";
   String^ pat = "(\\w+)\\s+(car)";
   
   // Compile the regular expression.
   Regex^ r = gcnew Regex( pat,RegexOptions::IgnoreCase );
   
   // Match the regular expression pattern against a text string.
   Match^ m = r->Match(text);
   int matchCount = 0;
   while ( m->Success )
   {
      Console::WriteLine( "Match{0}", ++matchCount );
      for ( int i = 1; i <= 2; i++ )
      {
         Group^ g = m->Groups[ i ];
         Console::WriteLine( "Group{0}='{1}'", i, g );
         CaptureCollection^ cc = g->Captures;
         for ( int j = 0; j < cc->Count; j++ )
         {
            Capture^ c = cc[ j ];
            System::Console::WriteLine( "Capture{0}='{1}', Position={2}", j, c, c->Index );
         }
      }
      m = m->NextMatch();
   }
}  
// This example displays the following output:
//       Match1
//       Group1='One'
//       Capture0='One', Position=0
//       Group2='car'
//       Capture0='car', Position=4
//       Match2
//       Group1='red'
//       Capture0='red', Position=8
//       Group2='car'
//       Capture0='car', Position=12
//       Match3
//       Group1='blue'
//       Capture0='blue', Position=16
//       Group2='car'
//       Capture0='car', Position=21
using System;
using System.Text.RegularExpressions;

class Example 
{
   static void Main() 
   {
      string text = "One car red car blue car";
      string pat = @"(\w+)\s+(car)";

      // Instantiate the regular expression object.
      Regex r = new Regex(pat, RegexOptions.IgnoreCase);
      
      // Match the regular expression pattern against a text string.
      Match m = r.Match(text);
      int matchCount = 0;
      while (m.Success) 
      {
         Console.WriteLine("Match"+ (++matchCount));
         for (int i = 1; i <= 2; i++) 
         {
            Group g = m.Groups[i];
            Console.WriteLine("Group"+i+"='" + g + "'");
            CaptureCollection cc = g.Captures;
            for (int j = 0; j < cc.Count; j++) 
            {
               Capture c = cc[j];
               System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
            }
         }
         m = m.NextMatch();
      }
   }
}
// This example displays the following output:
//       Match1
//       Group1='One'
//       Capture0='One', Position=0
//       Group2='car'
//       Capture0='car', Position=4
//       Match2
//       Group1='red'
//       Capture0='red', Position=8
//       Group2='car'
//       Capture0='car', Position=12
//       Match3
//       Group1='blue'
//       Capture0='blue', Position=16
//       Group2='car'
//       Capture0='car', Position=21
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim text As String = "One car red car blue car"
      Dim pattern As String = "(\w+)\s+(car)"

      ' Instantiate the regular expression object.
      Dim r As Regex = new Regex(pattern, RegexOptions.IgnoreCase)

      ' Match the regular expression pattern against a text string.
      Dim m As Match = r.Match(text)
      Dim matchcount as Integer = 0
      Do While m.Success
         matchCount += 1
         Console.WriteLine("Match" & (matchCount))
         Dim i As Integer
         For i = 1 to 2
            Dim g as Group = m.Groups(i)
            Console.WriteLine("Group" & i & "='" & g.ToString() & "'")
            Dim cc As CaptureCollection = g.Captures
            Dim j As Integer 
            For j = 0 to cc.Count - 1
              Dim c As Capture = cc(j)
               Console.WriteLine("Capture" & j & "='" & c.ToString() _
                  & "', Position=" & c.Index)
            Next 
         Next 
         m = m.NextMatch()
      Loop
   End Sub
End Module
' This example displays the following output:
'       Match1
'       Group1='One'
'       Capture0='One', Position=0
'       Group2='car'
'       Capture0='car', Position=4
'       Match2
'       Group1='red'
'       Capture0='red', Position=8
'       Group2='car'
'       Capture0='car', Position=12
'       Match3
'       Group1='blue'
'       Capture0='blue', Position=16
'       Group2='car'
'       Capture0='car', Position=21

正則運算式模式(\w+)\s+(car)會比對 "car" 一字的出現次數, 以及其前面的文字。The regular expression pattern (\w+)\s+(car) matches occurrences of the word "car" along with the word that precedes it. 如下表所示加以解讀。It is interpreted as shown in the following table.

模式Pattern 說明Description
(\w+) 比對一個或多個文字字元。Match one or more word characters. 這是第一個擷取群組。This is the first capturing group.
\s+ 比對一個或多個空白字元。Match one or more white-space characters.
(car) 符合常值字串 "car"。Match the literal string "car". 這是第二個擷取群組。This is the second capturing group.

備註

Match(String)方法會傳回輸入字串中符合正則運算式模式的第一個子字串。The Match(String) method returns the first substring that matches a regular expression pattern in an input string. 如需用來建立正則運算式模式之語言元素的詳細資訊, 請參閱正則運算式語言-快速參考For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

您可以藉由檢查傳回Match Success物件之屬性的值, 判斷是否在輸入字串中找到正則運算式模式。You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. 如果找到符合的項目,則所傳回 Match 物件的 Value 屬性會包含符合規則運算式模式之 input 的子字串。If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. 如果找不到相符的, 其值String.Empty為。If no match is found, its value is String.Empty.

這個方法會傳回中input符合正則運算式模式的第一個子字串。This method returns the first substring in input that matches the regular expression pattern. 您可以藉由重複呼叫傳回Match的物件的Match.NextMatch方法, 來抓取後續的相符專案。You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. 您也可以藉由呼叫Regex.Matches(String)方法, 在單一方法呼叫中取出所有相符專案。You can also retrieve all matches in a single method call by calling the Regex.Matches(String) method.

如果比對作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

另請參閱

Match(String, String)

在指定的輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the specified input string for the first occurrence of the specified regular expression.

public:
 static System::Text::RegularExpressions::Match ^ Match(System::String ^ input, System::String ^ pattern);
public static System.Text.RegularExpressions.Match Match (string input, string pattern);
static member Match : string * string -> System.Text.RegularExpressions.Match
Public Shared Function Match (input As String, pattern As String) As Match

參數

input
String

用來搜尋比對的字串。The string to search for a match.

pattern
String

要比對的規則運算式模式。The regular expression pattern to match.

傳回

物件,包含符合之項目的相關資訊。An object that contains information about the match.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會呼叫Match(String, String)方法Match.NextMatch , 以尋找至少包含一個z字元的第一個字組, 然後呼叫方法來尋找任何其他相符專案。The following example calls the Match(String, String) method to find the first word that contains at least one z character, and then calls the Match.NextMatch method to find any additional matches.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "ablaze beagle choral dozen elementary fanatic " +
                     "glaze hunger inept jazz kitchen lemon minus " +
                     "night optical pizza quiz restoration stamina " +
                     "train unrest vertical whiz xray yellow zealous";
      string pattern = @"\b\w*z+\w*\b";
      Match m = Regex.Match(input, pattern);
      while (m.Success) {
         Console.WriteLine("'{0}' found at position {1}", m.Value, m.Index);
         m = m.NextMatch();
      }   
   }
}
// The example displays the following output:
//    'ablaze' found at position 0
//    'dozen' found at position 21
//    'glaze' found at position 46
//    'jazz' found at position 65
//    'pizza' found at position 104
//    'quiz' found at position 110
//    'whiz' found at position 157
//    'zealous' found at position 174
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "ablaze beagle choral dozen elementary fanatic " +
                            "glaze hunger inept jazz kitchen lemon minus " +
                            "night optical pizza quiz restoration stamina " +
                            "train unrest vertical whiz xray yellow zealous"
      Dim pattern As String = "\b\w*z+\w*\b"
      Dim m As Match = Regex.Match(input, pattern)
      Do While m.Success 
         Console.WriteLine("'{0}' found at position {1}", m.Value, m.Index)
         m = m.NextMatch()
      Loop                      
   End Sub
End Module
' The example displays the following output:
    'ablaze' found at position 0
    'dozen' found at position 21
    'glaze' found at position 46
    'jazz' found at position 65
    'pizza' found at position 104
    'quiz' found at position 110
    'whiz' found at position 157
    'zealous' found at position 174

規則運算式模式 \b\w*z+\w*\b 的解譯方式如下表所示。The regular expression pattern \b\w*z+\w*\b is interpreted as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\w* 比對零個、一個或多個文字字元。Match zero, one, or more word characters.
z+ 符合一或多個出現的z字元。Match one or more occurrences of the z character.
\w* 比對零個、一個或多個文字字元。Match zero, one, or more word characters.
\b 結束字緣比對。End the match at a word boundary.

備註

Match(String, String)方法會傳回輸入字串中符合正則運算式模式的第一個子字串。The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. 如需用來建立正則運算式模式之語言元素的詳細資訊, 請參閱正則運算式語言-快速參考For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

靜態Match(String, String)方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例Match(String)方法。The static Match(String, String) method is equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance Match(String) method. 在此情況下, 正則運算式引擎會快取正則運算式模式。In this case, the regular expression engine caches the regular expression pattern.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

您可以藉由檢查傳回Match Success物件之屬性的值, 判斷是否在輸入字串中找到正則運算式模式。You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. 如果找到符合的項目,則所傳回 Match 物件的 Value 屬性會包含符合規則運算式模式之 input 的子字串。If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. 如果找不到相符的, 其值String.Empty為。If no match is found, its value is String.Empty.

這個方法會傳回中input符合正則運算式模式的第一個子字串。This method returns the first substring in input that matches the regular expression pattern. 您可以藉由重複呼叫傳回Match的物件的Match.NextMatch方法, 來抓取後續的相符專案。You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. 您也可以藉由呼叫Regex.Matches(String, String)方法, 在單一方法呼叫中取出所有相符專案。You can also retrieve all matches in a single method call by calling the Regex.Matches(String, String) method.

如果比對作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 用來抓取模式比對的建議靜態方法Match(String, String)是, 可讓您設定逾時間隔。The recommended static method for retrieving a pattern match is Match(String, String), which lets you set the time-out interval.

另請參閱

適用於