Regex.IsMatch 方法

定義

指示規則運算式是否在輸入字串中尋找比對。Indicates whether the regular expression finds a match in the input string.

多載

IsMatch(String)

表示 Regex 建構函式中指定的規則運算式是否要在指定的輸入字串中尋找相符項目。Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

IsMatch(String, Int32)

表示 Regex 建構函式中所指定的規則運算式,是否要從字串中指定的起始位置開始,在指定的輸入字串中尋找相符項目。Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.

IsMatch(String, String)

表示指定的規則運算式是否在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string.

IsMatch(String, String, RegexOptions)

表示指定的規則運算式是否使用指定的比對選項,在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.

IsMatch(String, String, RegexOptions, TimeSpan)

指出指定的規則運算式是否使用指定的比對選項和逾時間隔,在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options and time-out interval.

IsMatch(String)

表示 Regex 建構函式中指定的規則運算式是否要在指定的輸入字串中尋找相符項目。Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

public:
 bool IsMatch(System::String ^ input);
public bool IsMatch (string input);
member this.IsMatch : string -> bool
Public Function IsMatch (input As String) As Boolean

參數

input
String

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

傳回

如果規則運算式尋找到符合項目,則為 true,否則為 falsetrue if the regular expression finds a match; otherwise, false.

例外狀況

inputnullinput is null.

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

範例

下列範例說明如何使用IsMatch(String)方法來判斷字串是否為有效的元件編號。The following example illustrates the use of the IsMatch(String) method to determine whether a string is a valid part number. 正則運算式假設零件編號具有特定的格式, 其中包含三組字元, 並以連字號分隔。The regular expression assumes that the part number has a specific format that consists of three sets of characters separated by hyphens. 第一個包含四個字元的集合必須包含英數位元, 後面接著兩個數字字元, 後面接著英數位元。The first set, which contains four characters, must consist of an alphanumeric character followed by two numeric characters followed by an alphanumeric character. 第二個集合 (由三個字元組成) 必須是數值。The second set, which consists of three characters, must be numeric. 第三個集合 (由四個字元組成) 必須有三個數字字元, 後面接著英數位元。The third set, which consists of four characters, must have three numeric characters followed by an alphanumeric character.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] partNumbers= { "1298-673-4192", "A08Z-931-468A", 
                              "_A90-123-129X", "12345-KKA-1230", 
                              "0919-2893-1256" };
      Regex rgx = new Regex(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
      foreach (string partNumber in partNumbers)
         Console.WriteLine("{0} {1} a valid part number.", 
                           partNumber, 
                           rgx.IsMatch(partNumber) ? "is" : "is not");
   }
}
// The example displays the following output:
//       1298-673-4192 is a valid part number.
//       A08Z-931-468A is a valid part number.
//       _A90-123-129X is not a valid part number.
//       12345-KKA-1230 is not a valid part number.
//       0919-2893-1256 is not a valid part number.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim partNumbers() As String = { "1298-673-4192", "A08Z-931-468A", _
                                      "_A90-123-129X", "12345-KKA-1230", _
                                      "0919-2893-1256" }
      Dim rgx As New Regex("^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$")
      For Each partNumber As String In partNumbers
         Console.WriteLine("{0} {1} a valid part number.", _
                           partNumber, _
                           IIF(rgx.IsMatch(partNumber), "is", "is not"))
      Next
   End Sub
End Module
' The example displays the following output:
'       1298-673-4192 is a valid part number.
'       A08Z-931-468A is a valid part number.
'       _A90-123-129X is not a valid part number.
'       12345-KKA-1230 is not a valid part number.
'       0919-2893-1256 is not a valid part number.

規則運算式模式為:The regular expression pattern is:

^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$  

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
^ 在行的開頭開始比對。Begin the match at the beginning of the line.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
\d{2} 比對兩個數字字元。Match two numeric characters.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
- 比對連字號。Match a hyphen.
\d{3} 只比對三個數字字元。Match exactly three numeric characters.
(-\d{3}){2} 尋找後面接著三個數字字元的連字號, 並符合此模式的兩個出現次數。Find a hyphen followed by three numeric characters, and match two occurrences of this pattern.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
$ 在行尾結束相符。End the match at the end of the line.

備註

IsMatch方法通常用來驗證字串, 或確保字串符合特定模式, 而不需要針對後續操作取得該字串。The IsMatch method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation. 如果要判斷是否有一個或多個字串符合規則運算式模式,然後再擷取做後續操作,請呼叫 MatchMatches 方法。If you want to determine whether one or more strings match a regular expression pattern and then retrieve them for subsequent manipulation, call the Match or Matches 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.

另請參閱

IsMatch(String, Int32)

表示 Regex 建構函式中所指定的規則運算式,是否要從字串中指定的起始位置開始,在指定的輸入字串中尋找相符項目。Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.

public:
 bool IsMatch(System::String ^ input, int startat);
public bool IsMatch (string input, int startat);
member this.IsMatch : string * int -> bool
Public Function IsMatch (input As String, startat As Integer) As Boolean

參數

input
String

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

startat
Int32

要開始搜尋的字元位置。The character position at which to start the search.

傳回

如果規則運算式尋找到符合項目,則為 true,否則為 falsetrue if the regular expression finds a match; otherwise, false.

例外狀況

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.

範例

下列範例說明如何使用IsMatch(String, Int32)方法來判斷字串是否為有效的元件編號。The following example illustrates the use of the IsMatch(String, Int32) method to determine whether a string is a valid part number. 它會搜尋後面加上冒號的元件編號 (:)字串中的字元。It searches for a part number that follows a colon (:) character in a string. 方法是用來判斷冒號字元的位置, 然後傳遞IsMatch(String, Int32)至方法。 IndexOf(Char)The IndexOf(Char) method is used to determine the position of the colon character, which is then passed to the IsMatch(String, Int32) method. 正則運算式假設零件編號具有特定的格式, 其中包含三組字元, 並以連字號分隔。The regular expression assumes that the part number has a specific format that consists of three sets of characters separated by hyphens. 第一個包含四個字元的集合必須包含英數位元, 後面接著兩個數字字元, 後面接著英數位元。The first set, which contains four characters, must consist of an alphanumeric character followed by two numeric characters followed by an alphanumeric character. 第二個集合 (由三個字元組成) 必須是數值。The second set, which consists of three characters, must be numeric. 第三個集合 (由四個字元組成) 必須有三個數字字元, 後面接著英數位元。The third set, which consists of four characters, must have three numeric characters followed by an alphanumeric character.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] partNumbers= { "Part Number: 1298-673-4192", "Part No: A08Z-931-468A", 
                              "_A90-123-129X", "123K-000-1230", 
                              "SKU: 0919-2893-1256" };
      Regex rgx = new Regex(@"[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
      foreach (string partNumber in partNumbers)
      {
         int start = partNumber.IndexOf(':');
         if (start >= 0)
         {
            Console.WriteLine("{0} {1} a valid part number.", 
                              partNumber, 
                              rgx.IsMatch(partNumber, start) ? "is" : "is not");
         }
         else
         {
            Console.WriteLine("Cannot find starting position in {0}.", partNumber);
         }
      }
   }
}
// The example displays the following output:
//       Part Number: 1298-673-4192 is a valid part number.
//       Part No: A08Z-931-468A is a valid part number.
//       Cannot find starting position in _A90-123-129X.
//       Cannot find starting position in 123K-000-1230.
//       SKU: 0919-2893-1256 is not a valid part number.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim partNumbers() As String = { "Part Number: 1298-673-4192", "Part No: A08Z-931-468A", _
                                      "_A90-123-129X", "123K-000-1230", _
                                      "SKU: 0919-2893-1256" }
      Dim rgx As New Regex("[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$")
      For Each partNumber As String In partNumbers
         Dim start As Integer = partNumber.IndexOf(":"c)
         If start >= 0 Then 
            Console.WriteLine("{0} {1} a valid part number.", _
                              partNumber, _
                              IIF(rgx.IsMatch(partNumber, start), "is", "is not"))
         Else
            Console.WriteLine("Cannot find starting position in {0}.", partNumber)
         End If                              
      Next
   End Sub
End Module
' The example displays the following output:
'       Part Number: 1298-673-4192 is a valid part number.
'       Part No: A08Z-931-468A is a valid part number.
'       Cannot find starting position in _A90-123-129X.
'       Cannot find starting position in 123K-000-1230.
'       SKU: 0919-2893-1256 is not a valid part number.

規則運算式模式為:The regular expression pattern is:

[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$  

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
\d{2} 比對兩個數字字元。Match two numeric characters.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
- 比對連字號。Match a hyphen.
\d{3} 只比對三個數字字元。Match exactly three numeric characters.
(-\d{3}){2} 尋找後面接著三個數字字元的連字號, 並符合此模式的兩個出現次數。Find a hyphen followed by three numeric characters, and match two occurrences of this pattern.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
$ 在行尾結束相符。End the match at the end of the line.

備註

IsMatch方法通常用來驗證字串, 或確保字串符合特定模式, 而不需要針對後續操作取得該字串。The IsMatch method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation. 如果要判斷是否有一個或多個字串符合規則運算式模式,然後再擷取做後續操作,請呼叫 MatchMatches 方法。If you want to determine whether one or more strings match a regular expression pattern and then retrieve them for subsequent manipulation, call the Match or Matches 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.

另請參閱

IsMatch(String, String)

表示指定的規則運算式是否在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string.

public:
 static bool IsMatch(System::String ^ input, System::String ^ pattern);
public static bool IsMatch (string input, string pattern);
static member IsMatch : string * string -> bool
Public Shared Function IsMatch (input As String, pattern As String) As Boolean

參數

input
String

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

pattern
String

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

傳回

如果規則運算式尋找到符合項目,則為 true,否則為 falsetrue if the regular expression finds a match; otherwise, false.

例外狀況

發生規則運算式剖析錯誤。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.

範例

下列範例說明如何使用IsMatch(String, String)方法來判斷字串是否為有效的元件編號。The following example illustrates the use of the IsMatch(String, String) method to determine whether a string is a valid part number. 正則運算式假設零件編號具有特定的格式, 其中包含三組字元, 並以連字號分隔。The regular expression assumes that the part number has a specific format that consists of three sets of characters separated by hyphens. 第一個包含四個字元的集合必須包含英數位元, 後面接著兩個數字字元, 後面接著英數位元。The first set, which contains four characters, must consist of an alphanumeric character followed by two numeric characters followed by an alphanumeric character. 第二個集合 (由三個字元組成) 必須是數值。The second set, which consists of three characters, must be numeric. 第三個集合 (由四個字元組成) 必須有三個數字字元, 後面接著英數位元。The third set, which consists of four characters, must have three numeric characters followed by an alphanumeric character.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] partNumbers= { "1298-673-4192", "A08Z-931-468A", 
                              "_A90-123-129X", "12345-KKA-1230", 
                              "0919-2893-1256" };
      string pattern = @"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$";
      foreach (string partNumber in partNumbers)
         Console.WriteLine("{0} {1} a valid part number.", 
                           partNumber, 
                           Regex.IsMatch(partNumber, pattern) ? "is" : "is not");
   }
}
// The example displays the following output:
//       1298-673-4192 is a valid part number.
//       A08Z-931-468A is a valid part number.
//       _A90-123-129X is not a valid part number.
//       12345-KKA-1230 is not a valid part number.
//       0919-2893-1256 is not a valid part number.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim partNumbers() As String = { "1298-673-4192", "A08Z-931-468A", _
                                      "_A90-123-129X", "12345-KKA-1230", _
                                      "0919-2893-1256" }
      Dim pattern As String = "^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$"
      For Each partNumber As String In partNumbers
         Console.WriteLine("{0} {1} a valid part number.", _
                           partNumber, _
                           IIF(Regex.IsMatch(partNumber, pattern), "is", "is not"))
      Next
   End Sub
End Module
' The example displays the following output:
'       1298-673-4192 is a valid part number.
'       A08Z-931-468A is a valid part number.
'       _A90-123-129X is not a valid part number.
'       12345-KKA-1230 is not a valid part number.
'       0919-2893-1256 is not a valid part number.

規則運算式模式為:The regular expression pattern is:

^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$  

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
^ 在行的開頭開始比對。Begin the match at the beginning of the line.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
\d{2} 比對兩個數字字元。Match two numeric characters.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
- 比對連字號。Match a hyphen.
\d{3} 只比對三個數字字元。Match exactly three numeric characters.
(-\d{3}){2} 尋找後面接著三個數字字元的連字號, 並符合此模式的兩個出現次數。Find a hyphen followed by three numeric characters, and match two occurrences of this pattern.
[a-zA-Z0-9] 比對單一字母字元 (a透過zAZ) 或數位字元。Match a single alphabetic character (a through z or A through Z) or numeric character.
$ 在行尾結束相符。End the match at the end of the line.

備註

IsMatch方法通常用來驗證字串, 或確保字串符合特定模式, 而不需要針對後續操作取得該字串。The IsMatch method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation. 如果要判斷是否有一個或多個字串符合規則運算式模式,然後再擷取做後續操作,請呼叫 MatchMatches 方法。If you want to determine whether one or more strings match a regular expression pattern and then retrieve them for subsequent manipulation, call the Match or Matches method.

靜態IsMatch(String, String)方法相當於使用所Regex pattern指定的正則運算式模式來建立物件, 並呼叫實例方法。IsMatch(String)The static IsMatch(String, String) method is equivalent to constructing a Regex object with the regular expression pattern specified by pattern and calling the IsMatch(String) instance method. 這種正則運算式模式會進行快取, 以供正則運算式引擎快速抓取。This regular expression pattern is cached for rapid retrieval by the regular expression engine.

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.

如果比對作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 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 the method 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. 驗證模式比對的建議靜態方法是IsMatch(String, String, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for verifying a pattern match is IsMatch(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

IsMatch(String, String, RegexOptions)

表示指定的規則運算式是否使用指定的比對選項,在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.

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

參數

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.

傳回

如果規則運算式尋找到符合項目,則為 true,否則為 falsetrue if the regular expression finds a match; otherwise, false.

例外狀況

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

inputpatternnullinput or pattern is null.

options 不是有效的 RegexOptions 值。options is not a valid RegexOptions value.

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

範例

下列範例說明如何使用IsMatch(String, String)方法來判斷字串是否為有效的元件編號。The following example illustrates the use of the IsMatch(String, String) method to determine whether a string is a valid part number. 正則運算式假設零件編號具有特定的格式, 其中包含三組字元, 並以連字號分隔。The regular expression assumes that the part number has a specific format that consists of three sets of characters separated by hyphens. 第一個包含四個字元的集合必須包含英數位元, 後面接著兩個數字字元, 後面接著英數位元。The first set, which contains four characters, must consist of an alphanumeric character followed by two numeric characters followed by an alphanumeric character. 第二個集合 (由三個字元組成) 必須是數值。The second set, which consists of three characters, must be numeric. 第三個集合 (由四個字元組成) 必須有三個數字字元, 後面接著英數位元。The third set, which consists of four characters, must have three numeric characters followed by an alphanumeric character.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] partNumbers= { "1298-673-4192", "A08Z-931-468a", 
                              "_A90-123-129X", "12345-KKA-1230", 
                              "0919-2893-1256" };
      string pattern = @"^[A-Z0-9]\d{2}[A-Z0-9](-\d{3}){2}[A-Z0-9]$";
      foreach (string partNumber in partNumbers)
         Console.WriteLine("{0} {1} a valid part number.", 
                           partNumber, 
                           Regex.IsMatch(partNumber, pattern, RegexOptions.IgnoreCase) 
                                         ? "is" : "is not");
   }
}
// The example displays the following output:
//       1298-673-4192 is a valid part number.
//       A08Z-931-468a is a valid part number.
//       _A90-123-129X is not a valid part number.
//       12345-KKA-1230 is not a valid part number.
//       0919-2893-1256 is not a valid part number.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim partNumbers() As String = { "1298-673-4192", "A08Z-931-468a", _
                                      "_A90-123-129X", "12345-KKA-1230", _
                                      "0919-2893-1256" }
      Dim pattern As String = "^[A-Z0-9]\d{2}[A-Z0-9](-\d{3}){2}[A-Z0-9]$"
      For Each partNumber As String In partNumbers
         Console.WriteLine("{0} {1} a valid part number.", _
                           partNumber, _
                           IIF(Regex.IsMatch(partNumber, pattern, RegexOptions.IgnoreCase), _
                               "is", "is not"))
      Next
   End Sub
End Module
' The example displays the following output:
'       1298-673-4192 is a valid part number.
'       A08Z-931-468a is a valid part number.
'       _A90-123-129X is not a valid part number.
'       12345-KKA-1230 is not a valid part number.
'       0919-2893-1256 is not a valid part number.

規則運算式模式為:The regular expression pattern is:

^[A-Z0-9]\d{2}[A-Z0-9](-\d{3}){2}[A-Z0-9]$  

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
^ 從字串的開頭開始比對。Begin the match at the beginning of the string.
[A-Z0-9] 比對從AZ的任何單一字母字元, 或任何數位字元。Match any single alphabetic character from A through Z, or any numeric character.
\d{2} 比對兩個數字字元。Match two numeric characters.
[A-Z0-9] 比對從AZ的任何單一字母字元, 或任何數位字元。Match any single alphabetic character from A through Z, or any numeric character.
- 比對連字號。Match a hyphen.
\d{3} 只比對三個數字字元。Match exactly three numeric characters.
(-\d{3}){2} 尋找後面接著三個數字字元的連字號, 並符合此模式的兩個出現次數。Find a hyphen followed by three numeric characters, and match two occurrences of this pattern..
[A-Z0-9] 比對從AZ的任何單一字母字元, 或任何數位字元。Match any single alphabetic character from A through Z, or any numeric character.
$ 在字串的結尾結束比對。End the match at the end of the string.

呼叫方法, options並將參數設為RegexOptions.IgnoreCase , 相當於定義下列正則運算式: IsMatch(String, String, RegexOptions)Calling the IsMatch(String, String, RegexOptions) method with the options parameter set to RegexOptions.IgnoreCase is equivalent to defining the following regular expression:

[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]  

如需比較, 請參閱IsMatch(String, String)方法的範例。For comparison, see the example for the IsMatch(String, String) method.

備註

IsMatch方法通常用來驗證字串, 或確保字串符合特定模式, 而不需要針對後續操作取得該字串。The IsMatch method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation. 如果要判斷是否有一個或多個字串符合規則運算式模式,然後再擷取做後續操作,請呼叫 MatchMatches 方法。If you want to determine whether one or more strings match a regular expression pattern and then retrieve them for subsequent manipulation, call the Match or Matches method.

靜態IsMatch(String, String, RegexOptions)方法相當於使用所指定的Regex pattern正則運算式模式以及和呼叫IsMatch(String)實例的正則運算式選項options來建立物件。方法.The static IsMatch(String, String, RegexOptions) method is equivalent to constructing a Regex object with the regular expression pattern specified by pattern and the regular expression options specified by options and calling the IsMatch(String) instance method. 這種正則運算式模式會進行快取, 以供正則運算式引擎快速抓取。This regular expression pattern is cached for rapid retrieval by the regular expression engine.

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.

如果比對作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 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. 驗證模式比對的建議靜態方法是IsMatch(String, String, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for verifying a pattern match is IsMatch(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

IsMatch(String, String, RegexOptions, TimeSpan)

指出指定的規則運算式是否使用指定的比對選項和逾時間隔,在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options and time-out interval.

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

參數

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.

傳回

如果規則運算式尋找到符合項目,則為 true,否則為 falsetrue if the regular expression finds a match; otherwise, false.

例外狀況

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

inputpatternnullinput or pattern is null.

options 不是有效的 RegexOptions 值。options is not a valid RegexOptions value.

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

發生逾時。A time-out occurred.

範例

下列範例說明如何使用IsMatch(String, String, RegexOptions, TimeSpan)方法來判斷字串是否為有效的元件編號。The following example illustrates the use of the IsMatch(String, String, RegexOptions, TimeSpan) method to determine whether a string is a valid part number. 正則運算式假設零件編號具有特定的格式, 其中包含三組字元, 並以連字號分隔。The regular expression assumes that the part number has a specific format that consists of three sets of characters separated by hyphens. 第一個包含四個字元的集合必須包含英數位元, 後面接著兩個數字字元, 後面接著英數位元。The first set, which contains four characters, must consist of an alphanumeric character followed by two numeric characters followed by an alphanumeric character. 第二個集合 (由三個字元組成) 必須是數值。The second set, which consists of three characters, must be numeric. 第三個集合 (由四個字元組成) 必須有三個數字字元, 後面接著英數位元。The third set, which consists of four characters, must have three numeric characters followed by an alphanumeric character. 比對正則運算式模式應該包含最少的輸入字串搜尋, 因此方法會將逾時間隔設定為500毫秒。Matching the regular expression pattern should involve minimal searching through the input string, so the method sets a time-out interval of 500 milliseconds.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] partNumbers= { "1298-673-4192", "A08Z-931-468a", 
                              "_A90-123-129X", "12345-KKA-1230", 
                              "0919-2893-1256" };
      string pattern = @"^[A-Z0-9]\d{2}[A-Z0-9](-\d{3}){2}[A-Z0-9]$";
      foreach (string partNumber in partNumbers)
         try {
            Console.WriteLine("{0} {1} a valid part number.", 
                              partNumber, 
                              Regex.IsMatch(partNumber, pattern, RegexOptions.IgnoreCase) 
                                            ? "is" : "is not", TimeSpan.FromMilliseconds(500));
         }
         catch (RegexMatchTimeoutException e) {
            Console.WriteLine("Timeout after {0} seconds matching {1}.",
                              e.MatchTimeout, e.Input);
         }
   }
}
// The example displays the following output:
//       1298-673-4192 is a valid part number.
//       A08Z-931-468a is a valid part number.
//       _A90-123-129X is not a valid part number.
//       12345-KKA-1230 is not a valid part number.
//       0919-2893-1256 is not a valid part number.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim partNumbers() As String = { "1298-673-4192", "A08Z-931-468a", 
                                      "_A90-123-129X", "12345-KKA-1230", 
                                      "0919-2893-1256" }
      Dim pattern As String = "^[A-Z0-9]\d{2}[A-Z0-9](-\d{3}){2}[A-Z0-9]$"
      For Each partNumber As String In partNumbers
         Try
            Console.WriteLine("{0} {1} a valid part number.", 
                              partNumber, _
                              IIF(Regex.IsMatch(partNumber, pattern, RegexOptions.IgnoreCase), _
                                  "is", "is not"),
                              TimeSpan.FromMilliseconds(500))
         Catch e As RegexMatchTimeoutException
            Console.WriteLine("Timeout after {0} seconds matching {1}.",
                              e.MatchTimeout, e.Input)
         End Try
      Next
   End Sub
End Module
' The example displays the following output:
'       1298-673-4192 is a valid part number.
'       A08Z-931-468a is a valid part number.
'       _A90-123-129X is not a valid part number.
'       12345-KKA-1230 is not a valid part number.
'       0919-2893-1256 is not a valid part number.

規則運算式模式為:The regular expression pattern is:

^[A-Z0-9]\d{2}[A-Z0-9](-\d{3}){2}[A-Z0-9]$  

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
^ 從字串的開頭開始比對。Begin the match at the beginning of the string.
[A-Z0-9] 比對從AZ的任何單一字母字元, 或任何數位字元。Match any single alphabetic character from A through Z, or any numeric character.
\d{2} 比對兩個數字字元。Match two numeric characters.
[A-Z0-9] 比對從AZ的任何單一字母字元, 或任何數位字元。Match any single alphabetic character from A through Z, or any numeric character.
- 比對連字號。Match a hyphen.
\d{3} 只比對三個數字字元。Match exactly three numeric characters.
(-\d{3}){2} 尋找後面接著三個數字字元的連字號, 並符合此模式的兩個出現次數。Find a hyphen followed by three numeric characters, and match two occurrences of this pattern.
[A-Z0-9] 比對從AZ的任何單一字母字元, 或任何數位字元。Match any single alphabetic character from A through Z, or any numeric character.
$ 在字串的結尾結束比對。End the match at the end of the string.

呼叫方法, options並將參數設為RegexOptions.IgnoreCase , 相當於定義下列正則運算式: IsMatch(String, String, RegexOptions, TimeSpan)Calling the IsMatch(String, String, RegexOptions, TimeSpan) method with the options parameter set to RegexOptions.IgnoreCase is equivalent to defining the following regular expression:

[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]  

如需比較, 請參閱IsMatch(String, String)方法的範例。For comparison, see the example for the IsMatch(String, String) method.

備註

IsMatch方法通常用來驗證字串, 或確保字串符合特定模式, 而不需要針對後續操作取得該字串。The IsMatch method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation. 如果要判斷是否有一個或多個字串符合規則運算式模式,然後再擷取做後續操作,請呼叫 MatchMatches 方法。If you want to determine whether one or more strings match a regular expression pattern and then retrieve them for subsequent manipulation, call the Match or Matches method.

靜態IsMatch(String, String, RegexOptions, TimeSpan)方法相當於使用所指定的Regex pattern正則運算式模式以及和呼叫IsMatch(String)實例的正則運算式選項options來建立物件。方法.The static IsMatch(String, String, RegexOptions, TimeSpan) method is equivalent to constructing a Regex object with the regular expression pattern specified by pattern and the regular expression options specified by options and calling the IsMatch(String) instance method. 這種正則運算式模式會進行快取, 以供正則運算式引擎快速抓取。This regular expression pattern is cached for rapid retrieval by the regular expression engine.

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.

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.

另請參閱

適用於