Regex.Match 方法

定义

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

重载

Match(String, String, RegexOptions)

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

Match(String)

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

Match(String, Int32)

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

Match(String, String)

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

Match(String, Int32, Int32)

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

Match(String, String, RegexOptions, TimeSpan)

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

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 正则表达式正则表达式语言 - 快速参考

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

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

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

调用方说明

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

另请参阅

适用于

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

要搜索匹配项的字符串。

返回

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

例外

inputnull

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

示例

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

#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) 返回与输入字符串中的正则表达式模式匹配的第一个子字符串。 有关用于生成正则表达式模式的语言元素的信息,请参阅 正则表达式语言 - 快速参考

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

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

RegexMatchTimeoutException如果匹配操作的执行时间超过构造函数指定的Regex.Regex(String, RegexOptions, TimeSpan)超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,则当操作超过为创建对象的应用程序域 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

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

返回

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

例外

inputnull

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) 方法等效于使用指定的正则表达式模式构造 Regex 对象并调用 实例 Match(String) 方法。 在这种情况下,正则表达式引擎将缓存正则表达式模式。

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

通过检查返回对象的 Success 属性的值,可以确定是否在输入字符串中找到正Match则表达式模式。 如果找到匹配项,则返回 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

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

返回

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

例外

inputnull

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

- 或 -

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

- 或 -

beginning+length-1 表示 input 范围外的某个位置。

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

注解

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

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

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

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

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

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

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

另请参阅

适用于

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 正则表达式正则表达式语言 - 快速参考

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

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

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

调用方说明

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

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

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

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

另请参阅

适用于