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.

返回

Boolean

如果正则表达式找到匹配项,则为 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] 匹配单个字母字符(azAZ)或数字字符。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] 匹配单个字母字符(azAZ)或数字字符。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] 匹配单个字母字符(azAZ)或数字字符。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.

如果匹配操作的执行时间超过了 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。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.

返回

Boolean

如果正则表达式找到匹配项,则为 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. IndexOf(Char) 方法用于确定冒号字符的位置,然后将其传递给 IsMatch(String, Int32) 方法。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] 匹配单个字母字符(azAZ)或数字字符。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] 匹配单个字母字符(azAZ)或数字字符。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] 匹配单个字母字符(azAZ)或数字字符。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.

如果匹配操作的执行时间超过了 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。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.

返回

Boolean

如果正则表达式找到匹配项,则为 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] 匹配单个字母字符(azAZ)或数字字符。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] 匹配单个字母字符(azAZ)或数字字符。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] 匹配单个字母字符(azAZ)或数字字符。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) 方法等效于使用 pattern 指定的正则表达式模式构造 Regex 对象,并调用 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.

返回

Boolean

如果正则表达式找到匹配项,则为 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) 方法等效于使用 pattern 指定的正则表达式模式构造 Regex 对象,并使用 options 指定的正则表达式选项并调用 IsMatch(String) 实例方法。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.

返回

Boolean

如果正则表达式找到匹配项,则为 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) 方法等效于使用 pattern 指定的正则表达式模式构造 Regex 对象,并使用 options 指定的正则表达式选项并调用 IsMatch(String) 实例方法。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. 有关详细信息,请参阅正则表达式和回溯的最佳实践BacktrackingFor 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.

另请参阅

适用于