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.EmptyIf 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.

Match(String, Int32, Int32) 方法会搜索 beginning 定义的 input 部分,并 length 参数用于正则表达式模式。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.EmptyIf no match is found, its value is String.Empty.

如果匹配操作的执行时间超过了 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 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.EmptyIf 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.

注解

Match(String, Int32) 方法返回与正则表达式模式匹配的第一个子字符串,该模式在输入字符串中从 startat 字符位置开始或之后。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 的字符开始。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 位置位于 input的右端。If 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.EmptyIf no match is found, its value is String.Empty.

此方法返回在 input 中与正则表达式模式匹配的 startat 字符位置处或之后找到的第一个子字符串。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.

如果匹配操作的执行时间超过了 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.

另请参阅

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) 匹配文本字符串 "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.EmptyIf 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.

如果匹配操作的执行时间超过了 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.

另请参阅

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) 方法查找至少包含一个 z 字符的第一个单词,然后调用 Match.NextMatch 方法查找任何其他匹配项。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.EmptyIf 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.

另请参阅

适用于