Regex.Match 方法

定义

在输入字符串中搜索与正则表达式模式匹配的子字符串,并将第一个匹配项作为单个 Match 对象返回。

重载

Match(String)

在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。

Match(String, Int32)

在输入字符串中搜索正则表达式的第一个匹配项,从字符串中的指定起始位置开始。

Match(String, String)

在指定的输入字符串中搜索指定正则表达式的第一个匹配项。

Match(String, Int32, Int32)

在输入字符串中搜索正则表达式的第一个匹配项,从指定的起始位置开始,只搜索指定的字符数。

Match(String, String, RegexOptions)

使用指定的匹配选项搜索输入字符串,查找指定正则表达式的第一个匹配项。

Match(String, String, RegexOptions, TimeSpan)

使用指定的匹配选项和超时间隔在输入字符串中搜索指定正则表达式的第一个匹配项。

Match(String)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。

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

要搜索匹配项的字符串。

返回

一个对象,包含有关匹配的信息。

例外

input null

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例在字符串中查找正则表达式模式匹配项,然后列出匹配的组、捕获和捕获位置。

#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”的匹配项以及前面出现的单词。 它的解释如下表所示。

模式 描述
(\w+) 匹配一个或多个单词字符。 这是第一个捕获组。
\s+ 匹配一个或多个空白字符。
(车) 匹配文本字符串“car”。 这是第二个捕获组。

注解

Match(String) 方法返回与输入字符串中的正则表达式模式匹配的第一个子字符串。 有关用于生成正则表达式模式的语言元素的信息,请参阅 正则表达式语言 - 快速参考

可以通过检查返回 Match 对象的 Success 属性的值来确定在输入字符串中找到正则表达式模式。 如果找到匹配项,则返回的 Match 对象的 Value 属性包含与正则表达式模式匹配的 input 子字符串。 如果未找到匹配项,则其值 String.Empty

此方法返回与正则表达式模式匹配的 input 中的第一个子字符串。 可以通过重复调用返回 Match 对象的 Match.NextMatch 方法来检索后续匹配项。 还可以通过调用 Regex.Matches(String) 方法检索单个方法调用中的所有匹配项。

如果匹配操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

另请参阅

适用于

Match(String, Int32)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

在输入字符串中搜索正则表达式的第一个匹配项,从字符串中的指定起始位置开始。

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

要搜索匹配项的字符串。

startat
Int32

从零开始搜索的字符位置。

返回

一个对象,包含有关匹配的信息。

例外

input null

startat 小于零或大于 input的长度。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

注解

有关此 API 的详细信息,请参阅 Regex.Match的补充 API 备注。

另请参阅

适用于

Match(String, String)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

在指定的输入字符串中搜索指定正则表达式的第一个匹配项。

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

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

返回

一个对象,包含有关匹配的信息。

例外

发生正则表达式分析错误。

inputpatternnull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例调用 Match(String, String) 方法以查找包含至少一个 z 字符的第一个单词,然后调用 Match.NextMatch 方法以查找任何其他匹配项。

using System;
using System.Text.RegularExpressions;

namespace Examples
{
    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 解释如下表所示。

模式 描述
\b 在单词边界处开始匹配。
\w* 匹配零、一个或多个单词字符。
z+ 匹配 z 字符的一个或多个匹配项。
\w* 匹配零、一个或多个单词字符。
\b 在单词边界处结束匹配。

注解

Match(String, String) 方法返回与输入字符串中的正则表达式模式匹配的第一个子字符串。 有关用于生成正则表达式模式的语言元素的信息,请参阅 正则表达式语言 - 快速参考

静态 Match(String, String) 方法等效于使用指定的正则表达式模式和调用实例 Match(String) 方法构造 Regex 对象。 在这种情况下,正则表达式引擎将缓存正则表达式模式。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考

可以通过检查返回 Match 对象的 Success 属性的值来确定在输入字符串中找到正则表达式模式。 如果找到匹配项,则返回的 Match 对象的 Value 属性包含与正则表达式模式匹配的 input 子字符串。 如果未找到匹配项,则其值 String.Empty

此方法返回与正则表达式模式匹配的 input 中的第一个子字符串。 可以通过重复调用返回 Match 对象的 Match.NextMatch 方法来检索后续匹配项。 还可以通过调用 Regex.Matches(String, String) 方法检索单个方法调用中的所有匹配项。

如果匹配操作的执行时间超过为调用该方法的应用程序域指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

调用方说明

此方法在一个时间间隔后超时,该值等于调用它的应用程序域的默认超时值。 如果未为应用程序域定义超时值,则使用阻止方法超时的值 InfiniteMatchTimeout。 用于检索模式匹配的建议静态方法 Match(String, String),这使你可以设置超时间隔。

另请参阅

适用于

Match(String, Int32, Int32)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

在输入字符串中搜索正则表达式的第一个匹配项,从指定的起始位置开始,只搜索指定的字符数。

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

要搜索匹配项的字符串。

beginning
Int32

输入字符串中从零开始的字符位置,用于定义要搜索的最左侧位置。

length
Int32

要包含在搜索中的子字符串中的字符数。

返回

一个对象,包含有关匹配的信息。

例外

input null

beginning 小于零或大于 input的长度。

-或-

length 小于零或大于 input的长度。

-或-

beginning + length -1 标识超出 input范围的位置。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

注解

Match(String, Int32, Int32) 方法返回与输入字符串的一部分中的正则表达式模式匹配的第一个子字符串。 有关用于生成正则表达式模式的语言元素的信息,请参阅 正则表达式语言 - 快速参考

Match(String, Int32, Int32) 方法搜索的正则表达式模式是由对 Regex 类构造函数之一的调用定义的。 有关可形成正则表达式模式的元素的详细信息,请参阅 正则表达式语言 - 快速参考

Match(String, Int32, Int32) 方法搜索由正则表达式模式的 beginninglength 参数定义的 input 部分。 beginning 始终定义要在搜索中包含的最左侧字符的索引,length 定义要搜索的最大字符数。 它们一起定义搜索的范围。 此行为与 input 实际上 input.Substring(beginning, length)一样,只是相对于 input开始计算任何匹配项的索引。 这意味着模式开头或末尾的任何定位点或零宽度断言的行为就像在此范围之外没有 input 一样。 例如,定位点 ^\G\A 将在 beginning 满足,$\z 将在 beginning + length - 1得到满足。

如果搜索从左到右(默认值),则正则表达式引擎将从索引处的字符 beginning 搜索索引处的字符 beginning + length - 1。 如果使用 RegexOptions.RightToLeft 选项实例化正则表达式引擎,以便搜索从右到左,则正则表达式引擎将从索引处的字符 beginning + length - 1 到索引处的字符 beginning

此方法返回它在此范围内找到的第一个匹配项。 可以通过重复调用返回 Match 对象的 Match.NextMatch 方法来检索后续匹配项。

可以通过检查返回 Match 对象的 Success 属性的值来确定在输入字符串中找到正则表达式模式。 如果找到匹配项,则返回的 Match 对象的 Value 属性包含与正则表达式模式匹配的 input 子字符串。 如果未找到匹配项,则其值 String.Empty

如果匹配操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时值,则如果操作超出为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

另请参阅

适用于

Match(String, String, RegexOptions)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

使用指定的匹配选项搜索输入字符串,查找指定正则表达式的第一个匹配项。

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

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

options
RegexOptions

提供匹配选项的枚举值的按位组合。

返回

一个对象,包含有关匹配的信息。

例外

发生正则表达式分析错误。

inputpatternnull

options 不是 RegexOptions 值的有效按位组合。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例定义一个正则表达式,该正则表达式匹配以字母“a”开头的单词。 它使用 RegexOptions.IgnoreCase 选项来确保正则表达式查找以大写“a”和小写“a”开头的单词。

using System;
using System.Text.RegularExpressions;

namespace Examples
{
    public class Example2
    {
        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 解释如下表所示。

模式 描述
\b 在单词边界处开始匹配。
a 匹配字符“a”。
\w* 匹配零、一个或多个单词字符。
\b 在单词边界处结束匹配。

注解

Match(String, String, RegexOptions) 方法返回与输入字符串中的正则表达式模式匹配的第一个子字符串。 有关用于生成正则表达式模式的语言元素的信息,请参阅 正则表达式语言 - 快速参考

静态 Match(String, String, RegexOptions) 方法等效于使用 Regex(String, RegexOptions) 构造函数构造 Regex 对象并调用实例 Match(String) 方法。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考

可以通过检查返回 Match 对象的 Success 属性的值来确定在输入字符串中找到正则表达式模式。 如果找到匹配项,则返回的 Match 对象的 Value 属性包含与正则表达式模式匹配的 input 子字符串。 如果未找到匹配项,则其值 String.Empty

此方法返回与正则表达式模式匹配的 input 中找到的第一个子字符串。 可以通过重复调用返回 Match 对象的 NextMatch 方法来检索后续匹配项。 还可以通过调用 Regex.Matches(String, String, RegexOptions) 方法检索单个方法调用中的所有匹配项。

如果匹配操作的执行时间超过为调用该方法的应用程序域指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

调用方说明

此方法在一个时间间隔后超时,该值等于调用它的应用程序域的默认超时值。 如果未为应用程序域定义超时值,则使用阻止方法超时的值 InfiniteMatchTimeout。 用于检索模式匹配的建议静态方法 Match(String, String),这使你可以设置超时间隔。

另请参阅

适用于

Match(String, String, RegexOptions, TimeSpan)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

使用指定的匹配选项和超时间隔在输入字符串中搜索指定正则表达式的第一个匹配项。

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

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

options
RegexOptions

提供匹配选项的枚举值的按位组合。

matchTimeout
TimeSpan

超时间隔,或 InfiniteMatchTimeout 指示方法不应超时。

返回

一个对象,包含有关匹配的信息。

例外

发生正则表达式分析错误。

inputpatternnull

options 不是 RegexOptions 值的有效按位组合。

-或-

matchTimeout 为负数、零或大于约 24 天。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

注解

Match(String, String, RegexOptions, TimeSpan) 方法返回与输入字符串中的正则表达式模式匹配的第一个子字符串。 有关用于生成正则表达式模式的语言元素的信息,请参阅 正则表达式语言 - 快速参考

静态 Match(String, String, RegexOptions, TimeSpan) 方法等效于使用 Regex(String, RegexOptions, TimeSpan) 构造函数构造 Regex 对象并调用实例 Match(String) 方法。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考

可以通过检查返回 Match 对象的 Success 属性的值来确定在输入字符串中找到正则表达式模式。 如果找到匹配项,则返回的 Match 对象的 Value 属性包含与正则表达式模式匹配的 input 子字符串。 如果未找到匹配项,则其值 String.Empty

此方法返回与正则表达式模式匹配的 input 中找到的第一个子字符串。 可以通过重复调用返回 Match 对象的 NextMatch 方法来检索后续匹配项。 还可以通过调用 Regex.Matches(String, String, RegexOptions) 方法检索单个方法调用中的所有匹配项。

matchTimeout 参数指定模式匹配方法在超时之前应尝试查找匹配的时间。设置超时间隔可防止依赖过度回溯的正则表达式在处理包含接近匹配项的输入时停止响应。 有关详细信息,请参阅 正则表达式的最佳做法回溯。 如果未在该时间间隔中找到匹配项,该方法将引发 RegexMatchTimeoutException 异常。 matchTimeout 替代为方法在其中执行的应用程序域定义的任何默认超时值。

调用方说明

建议将 matchTimeout 参数设置为适当的值,例如两秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供略微更好的性能。 但是,应仅在以下情况下禁用超时:

  • 当正则表达式处理的输入派生自已知且受信任的源或包含静态文本时。 这不包括用户动态输入的文本。

  • 当正则表达式模式经过全面测试以确保它有效地处理匹配项、非匹配项和接近匹配项时。

  • 当正则表达式模式不包含任何已知在处理接近匹配时导致过度回溯的语言元素。

另请参阅

适用于