Regex Regex Regex Regex Class

定义

表示不可变的正则表达式。Represents an immutable regular expression.

public ref class Regex : System::Runtime::Serialization::ISerializable
[System.Serializable]
public class Regex : System.Runtime.Serialization.ISerializable
type Regex = class
    interface ISerializable
Public Class Regex
Implements ISerializable
继承
RegexRegexRegexRegex
派生
属性
实现

示例

下面的示例使用正则表达式检查字符串中重复出现的单词。The following example uses a regular expression to check for repeated occurrences of words in a string. 正则表达式\b(?<word>\w+)\s+(\k<word>)\b可以解释为下表中所示。The regular expression \b(?<word>\w+)\s+(\k<word>)\b can be interpreted as shown in the following table.

模式Pattern 说明Description
\b 在单词边界处开始匹配。Start the match at a word boundary.
(?<word>\w+) 匹配一个或多个单词字符, 最多一个字边界。Match one or more word characters up to a word boundary. 将此捕获的word组命名为。Name this captured group word.
\s+ 匹配一个或多个空白字符。Match one or more white-space characters.
(\k<word>) 匹配名为word的捕获组。Match the captured group that is named word.
\b 与字边界匹配。Match a word boundary.
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   // Define a regular expression for repeated words.
   Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

   // Define a test string.        
   String^ text = "The the quick brown fox  fox jumps over the lazy dog dog.";

   // Find matches.
   MatchCollection^ matches = rx->Matches( text );

   // Report the number of matches found.
   Console::WriteLine( "{0} matches found.", matches->Count );

   // Report on each match.
   for each (Match^ match in matches)
   {
      String^ word = match->Groups["word"]->Value;
      int index = match->Index;
      Console::WriteLine("{0} repeated at position {1}", word, index);   
   }
}
using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
        
        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }
        
    }
	
}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumps over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54
Imports System.Text.RegularExpressions

Public Module Test

    Public Sub Main()
        ' Define a regular expression for repeated words.
        Dim rx As New Regex("\b(?<word>\w+)\s+(\k<word>)\b", _
               RegexOptions.Compiled Or RegexOptions.IgnoreCase)

        ' Define a test string.        
        Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
        
        ' Find matches.
        Dim matches As MatchCollection = rx.Matches(text)

        ' Report the number of matches found.
        Console.WriteLine("{0} matches found in:", matches.Count)
        Console.WriteLine("   {0}", text)

        ' Report on each match.
        For Each match As Match In matches
            Dim groups As GroupCollection = match.Groups
            Console.WriteLine("'{0}' repeated at positions {1} and {2}", _ 
                              groups.Item("word").Value, _
                              groups.Item(0).Index, _
                              groups.Item(1).Index)
        Next
    End Sub
End Module
' The example produces the following output to the console:
'       3 matches found in:
'          The the quick brown fox  fox jumps over the lazy dog dog.
'       'The' repeated at positions 0 and 4
'       'fox' repeated at positions 20 and 25
'       'dog' repeated at positions 50 and 54

下面的示例演示如何使用正则表达式来检查字符串是表示货币值, 还是具有表示货币值的正确格式。The following example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. 在这种情况下, 将从NumberFormatInfo.CurrencyDecimalSeparator用户的当前区域性的CurrencyDecimalDigits NumberFormatInfo.CurrencySymbolNumberFormatInfo.NegativeSign、、和NumberFormatInfo.PositiveSign属性动态生成正则表达式。In this case, the regular expression is built dynamically from the NumberFormatInfo.CurrencyDecimalSeparator, CurrencyDecimalDigits, NumberFormatInfo.CurrencySymbol, NumberFormatInfo.NegativeSign, and NumberFormatInfo.PositiveSign properties for the user's current culture. 如果系统的当前区域性为 en-us, 则生成的正则表达式是^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$If the system's current culture is en-US, the resulting regular expression is ^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$. 此正则表达式可以解释为下表中所示。This regular expression can be interpreted as shown in the following table.

模式Pattern 说明Description
^ 从字符串的开头开始。Start at the beginning of the string.
\s* 匹配零个或多个空白字符。Match zero or more white-space characters.
[\+-]? 匹配正号或负号的零个或一个匹配项。Match zero or one occurrence of either the positive sign or the negative sign.
\s? 匹配零个或一个空白字符。Match zero or one white-space character.
\$? 匹配美元符号的零个或一个匹配项。Match zero or one occurrence of the dollar sign.
\s? 匹配零个或一个空白字符。Match zero or one white-space character.
\d* 匹配零个或多个十进制数字。Match zero or more decimal digits.
\.? 匹配零个或一个小数点符号。Match zero or one decimal point symbol.
\d{2}? 匹配两个十进制数字零次或一次。Match two decimal digits zero or one time.
(\d*\.?\d{2}?){1} 匹配由小数点符号分隔的整数和小数位的模式 (至少一次)。Match the pattern of integral and fractional digits separated by a decimal point symbol at least one time.
$ 与字符串的末尾匹配。Match the end of the string.

在这种情况下, 正则表达式假定有效的货币字符串不包含组分隔符符号, 并且它没有小数位数或当前区域性的CurrencyDecimalDigits属性定义的小数位数。In this case, the regular expression assumes that a valid currency string does not contain group separator symbols, and that it has either no fractional digits or the number of fractional digits defined by the current culture's CurrencyDecimalDigits property.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get the current NumberFormatInfo object to build the regular 
      // expression pattern dynamically.
      NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;

      // Define the regular expression pattern.
      string pattern; 
      pattern = @"^\s*[";
      // Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + @"]?\s?";
      // Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + @"?\s?";
      // Add integral digits to the pattern.
      pattern += @"(\d*";
      // Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?";
      // Add the fractional digits.
      pattern += @"\d{";
      // Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$";
      
      Regex rgx = new Regex(pattern);

      // Define some test strings.
      string[] tests = { "-42", "19.99", "0.001", "100 USD", 
                         ".34", "0.34", "1,052.21", "$10.62", 
                         "+1.43", "-$0.23" };

      // Check each test string against the regular expression.
      foreach (string test in tests)
      {
         if (rgx.IsMatch(test))
            Console.WriteLine("{0} is a currency value.", test);
         else
            Console.WriteLine("{0} is not a currency value.", test);
      }
   }
}
// The example displays the following output:
//       -42 is a currency value.
//       19.99 is a currency value.
//       0.001 is not a currency value.
//       100 USD is not a currency value.
//       .34 is a currency value.
//       0.34 is a currency value.
//       1,052.21 is not a currency value.
//       $10.62 is a currency value.
//       +1.43 is a currency value.
//       -$0.23 is a currency value.
Imports System.Globalization
Imports System.Text.RegularExpressions

Public Module Example
   Public Sub Main()
      ' Get the current NumberFormatInfo object to build the regular 
      ' expression pattern dynamically.
      Dim nfi As NumberFormatInfo = NumberFormatInfo.CurrentInfo

      ' Define the regular expression pattern.
      Dim pattern As String 
      pattern = "^\s*["
      ' Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + "]?\s?"
      ' Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + "?\s?"
      ' Add integral digits to the pattern.
      pattern += "(\d*"
      ' Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?"
      ' Add the fractional digits.
      pattern += "\d{"
      ' Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$"
      
      Dim rgx As New Regex(pattern)

      ' Define some test strings.
      Dim tests() As String = {"-42", "19.99", "0.001", "100 USD", _
                               ".34", "0.34", "1,052.21", "$10.62", _
                               "+1.43", "-$0.23" }

      ' Check each test string against the regular expression.
      For Each test As String In tests
         If rgx.IsMatch(test) Then
            Console.WriteLine("{0} is a currency value.", test)
         Else
            Console.WriteLine("{0} is not a currency value.", test)
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       -42 is a currency value.
'       19.99 is a currency value.
'       0.001 is not a currency value.
'       100 USD is not a currency value.
'       .34 is a currency value.
'       0.34 is a currency value.
'       1,052.21 is not a currency value.
'       $10.62 is a currency value.
'       +1.43 is a currency value.
'       -$0.23 is a currency value.

由于此示例中的正则表达式是动态生成的, 因此在设计时不知道当前区域性的货币符号、十进制符号或正负号是否可能会被正则表达式引擎错误地解释为正则表达式引擎expression language 运算符。Because the regular expression in this example is built dynamically, we do not know at design time whether the current culture's currency symbol, decimal sign, or positive and negative signs might be misinterpreted by the regular expression engine as regular expression language operators. 为了防止任何误解, 此示例将每个动态生成的Escape字符串传递给方法。To prevent any misinterpretation, the example passes each dynamically generated string to the Escape method.

注解

Regex类表示 .NET Framework 的正则表达式引擎。The Regex class represents the .NET Framework's regular expression engine. 它可用于快速分析大量文本以找到特定的字符模式;提取、编辑、替换或删除文本子字符串;和将提取的字符串添加到集合以生成报告。It can be used to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection to generate a report.

备注

如果你的主要兴趣是通过确定是否符合特定模式来验证字符串, 则可以使用System.Configuration.RegexStringValidator类。If your primary interest is to validate a string by determining whether it conforms to a particular pattern, you can use the System.Configuration.RegexStringValidator class.

若要使用正则表达式, 可以使用正则表达式语言-快速参考中记录的语法来定义要在文本流中标识的模式。To use regular expressions, you define the pattern that you want to identify in a text stream by using the syntax documented in Regular Expression Language - Quick Reference. 接下来, 你可以根据需要Regex实例化对象。Next, you can optionally instantiate a Regex object. 最后, 调用执行某种操作的方法, 例如替换与正则表达式模式匹配的文本, 或标识模式匹配。Finally, you call a method that performs some operation, such as replacing text that matches the regular expression pattern, or identifying a pattern match.

备注

有关某些常见正则表达式模式, 请参阅正则表达式示例For some common regular expression patterns, see Regular Expression Examples. 还有多个正则表达式模式的联机库, 如Regular-Expressions.infoThere are also a number of online libraries of regular expression patterns, such as the one at Regular-Expressions.info.

有关使用Regex类的详细信息, 请参阅本主题中的以下部分:For more information about using the Regex class, see the following sections in this topic:

若要详细了解正则表达式语言,请参阅正则表达式语言 - 快速参考,或下载和打印下面的小册子之一:For more information about the regular expression language, see Regular Expression Language - Quick Reference or download and print one of these brochures:

快速参考(Word (.docx) 格式)Quick Reference in Word (.docx) format
快速参考(PDF (.pdf) 格式)Quick Reference in PDF (.pdf) format

Regex 与字符串方法Regex vs. String Methods

System.String类包含若干搜索和比较方法, 您可以使用这些方法来执行与文本的模式匹配。The System.String class includes several search and comparison methods that you can use to perform pattern matching with text. String.Contains例如,、 String.IndexOfAny String.IndexOf String.LastIndexOf String.LastIndexOfAny和方法确定字符串实例是否包含指定的子字符串;、、和方法返回起始String.StartsWith String.EndsWith字符串中指定子字符串的位置。For example, the String.Contains, String.EndsWith, and String.StartsWith methods determine whether a string instance contains a specified substring; and the String.IndexOf, String.IndexOfAny, String.LastIndexOf, and String.LastIndexOfAny methods return the starting position of a specified substring in a string. 搜索特定字符串时, System.String请使用类的方法。Use the methods of the System.String class when you are searching for a specific string. 搜索字符串Regex中的特定模式时, 请使用类。Use the Regex class when you are searching for a specific pattern in a string. 有关详细信息和示例, 请参阅.NET Framework 正则表达式For more information and examples, see .NET Framework Regular Expressions.

返回到备注Back to Remarks

静态与实例方法Static vs. Instance Methods

定义正则表达式模式后, 可以通过以下两种方式之一将其提供给正则表达式引擎:After you define a regular expression pattern, you can provide it to the regular expression engine in either of two ways:

  • 通过实例化Regex表示正则表达式的对象。By instantiating a Regex object that represents the regular expression. 为此, 请将正则表达式模式传递到Regex构造函数。To do this, you pass the regular expression pattern to a Regex constructor. 对象是不可变的; 当使用正Regex则表达式实例化对象时, 无法更改该对象的正则表达式。 RegexA Regex object is immutable; when you instantiate a Regex object with a regular expression, that object's regular expression cannot be changed.

  • 通过同时提供正则表达式和文本来搜索static (Shared在 Visual Basic) Regex方法。By supplying both the regular expression and the text to search to a static (Shared in Visual Basic) Regex method. 这使你可以使用正则表达式, 而无需Regex显式创建对象。This enables you to use a regular expression without explicitly creating a Regex object.

所有Regex模式标识方法均包括静态和实例重载。All Regex pattern identification methods include both static and instance overloads.

正则表达式引擎必须先编译特定模式, 然后才能使用该模式。The regular expression engine must compile a particular pattern before the pattern can be used. 由于Regex对象是不可变的, 因此这是一个Regex在调用类构造函数或静态方法时发生的一次性过程。Because Regex objects are immutable, this is a one-time procedure that occurs when a Regex class constructor or a static method is called. 为了消除重复编译单个正则表达式的需要, 正则表达式引擎会缓存静态方法调用中使用的已编译正则表达式。To eliminate the need to repeatedly compile a single regular expression, the regular expression engine caches the compiled regular expressions used in static method calls. 因此, 正则表达式模式匹配方法为静态和实例方法提供了相当的性能。As a result, regular expression pattern-matching methods offer comparable performance for static and instance methods.

重要

在 .NET Framework 版本1.0 和1.1 中, 已缓存所有已编译的正则表达式, 无论它们是在实例中使用还是静态方法调用。In the .NET Framework versions 1.0 and 1.1, all compiled regular expressions, whether they were used in instance or static method calls, were cached. 从 .NET Framework 2.0 开始, 仅缓存静态方法调用中使用的正则表达式。Starting with the .NET Framework 2.0, only regular expressions used in static method calls are cached.

但是, 在以下两种情况下, 缓存可能会对性能产生负面影响:However, caching can adversely affect performance in the following two cases:

  • 当使用带有大量正则表达式的静态方法调用时。When you use static method calls with a large number of regular expressions. 默认情况下, 正则表达式引擎会缓存15个最近使用的静态正则表达式。By default, the regular expression engine caches the 15 most recently used static regular expressions. 如果应用程序使用15个以上的静态正则表达式, 则必须重新编译某些正则表达式。If your application uses more than 15 static regular expressions, some regular expressions must be recompiled. 若要防止这种重新编译, 可以Regex.CacheSize增加属性。To prevent this recompilation, you can increase the Regex.CacheSize property.

  • 使用之前已编译Regex的正则表达式实例化新的对象时。When you instantiate new Regex objects with regular expressions that have previously been compiled. 例如, 下面的代码定义了一个正则表达式来查找文本流中的重复单词。For example, the following code defines a regular expression to locate duplicated words in a text stream. 尽管该示例使用单个正则表达式, 但它将实例Regex化一个新的对象来处理每行文本。Although the example uses a single regular expression, it instantiates a new Regex object to process each line of text. 这会导致在循环的每次迭代时重新编译正则表达式。This results in the recompilation of the regular expression with each iteration of the loop.

    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   
    
    Dim sr As New StreamReader(filename)
    Dim input As String
    Dim pattern As String = "\b(\w+)\s\1\b"
    Do While sr.Peek() >= 0
       input = sr.ReadLine()
       Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
       Dim matches As MatchCollection = rgx.Matches(input)
       If matches.Count > 0 Then
          Console.WriteLine("{0} ({1} matches):", input, matches.Count)
          For Each match As Match In matches
             Console.WriteLine("   " + match.Value)
          Next   
       End If
    Loop
    sr.Close()   
    

    若要防止重新编译, 应实例化Regex单个对象, 该对象可由需要它的所有代码访问, 如下面的重写示例中所示。To prevent recompilation, you should instantiate a single Regex object that is accessible to all code that requires it, as shown in the following rewritten example.

    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
    
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   
    
    Dim sr As New StreamReader(filename)
    Dim input As String
    Dim pattern As String = "\b(\w+)\s\1\b"
    Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
    Do While sr.Peek() >= 0
       input = sr.ReadLine()
       Dim matches As MatchCollection = rgx.Matches(input)
       If matches.Count > 0 Then
          Console.WriteLine("{0} ({1} matches):", input, matches.Count)
          For Each match As Match In matches
             Console.WriteLine("   " + match.Value)
          Next   
       End If
    Loop
    sr.Close()   
    

返回到备注Back to Remarks

执行正则表达式运算Performing Regular Expression Operations

无论你决定要实例化Regex对象并调用其方法或调用静态方法Regex , 类都提供以下模式匹配功能:Whether you decide to instantiate a Regex object and call its methods or call static methods, the Regex class offers the following pattern-matching functionality:

  • 验证匹配项。Validation of a match. 调用IsMatch方法以确定是否存在匹配项。You call the IsMatch method to determine whether a match is present.

  • 检索单个匹配项。Retrieval of a single match. 调用Match方法以Match检索一个对象, 该对象表示字符串中的第一个匹配项或字符串的一部分。You call the Match method to retrieve a Match object that represents the first match in a string or in part of a string. 可以通过调用Match.NextMatch方法来检索后续匹配项。Subsequent matches can be retrieved by calling the Match.NextMatch method.

  • 检索所有匹配项。Retrieval of all matches. 调用Matches方法可System.Text.RegularExpressions.MatchCollection检索对象, 该对象表示在字符串或字符串的一部分中找到的所有匹配项。You call the Matches method to retrieve a System.Text.RegularExpressions.MatchCollection object that represents all the matches found in a string or in part of a string.

  • 替换匹配文本。Replacement of matched text. 调用Replace方法以替换匹配的文本。You call the Replace method to replace matched text. 替换文本还可以由正则表达式定义。The replacement text can also be defined by a regular expression. 此外, 某些Replace方法还包括一个MatchEvaluator参数, 使你能够以编程方式定义替换文本。In addition, some of the Replace methods include a MatchEvaluator parameter that enables you to programmatically define the replacement text.

  • 创建一个字符串数组, 该数组由输入字符串的各个部分组成。Creation of a string array that is formed from parts of an input string. 调用Split方法以在由正则表达式定义的位置拆分输入字符串。You call the Split method to split an input string at positions that are defined by the regular expression.

除了其模式匹配方法以外, Regex类还包括几种特殊用途的方法:In addition to its pattern-matching methods, the Regex class includes several special-purpose methods:

  • Escape方法将可解释为正则表达式或输入字符串中的正则表达式运算符的任何字符转义。The Escape method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string.

  • Unescape方法删除这些转义字符。The Unescape method removes these escape characters.

  • CompileToAssembly方法创建包含预定义的正则表达式的程序集。The CompileToAssembly method creates an assembly that contains predefined regular expressions. .NET Framework 包含System.Web.RegularExpressions命名空间中这些特殊用途程序集的示例。The .NET Framework contains examples of these special-purpose assemblies in the System.Web.RegularExpressions namespace.

返回到备注Back to Remarks

定义超时值Defining a Time-Out Value

.NET Framework 支持功能完备的正则表达式语言, 可在模式匹配中提供强大的功能和灵活性。The .NET Framework supports a full-featured regular expression language that provides substantial power and flexibility in pattern matching. 不过, 功能和灵活性的代价是: 性能不佳的风险。However, the power and flexibility come at a cost: the risk of poor performance. 很难创建的正则表达式非常简单。Regular expressions that perform poorly are surprisingly easy to create. 在某些情况下, 在处理与正则表达式模式大致匹配的文本时, 依赖于过度回溯的正则表达式操作可能会停止响应。In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern. 有关 .NET Framework 正则表达式引擎的详细信息, 请参阅正则表达式行为的详细信息。For more information about the .NET Framework regular expression engine, see Details of Regular Expression Behavior. 有关过量回溯的详细信息, 请参阅回溯For more information about excessive backtracking, see Backtracking.

从开始, 您可以定义正则表达式匹配的超时间隔。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, you can define a time-out interval for regular expression matches. 如果正则表达式引擎无法在此时间间隔内标识匹配项, 则匹配操作将RegexMatchTimeoutException引发异常。If the regular expression engine cannot identify a match within this time interval, the matching operation throws a RegexMatchTimeoutException exception. 在大多数情况下, 这样可以防止正则表达式引擎尝试匹配与正则表达式模式近似匹配的文本, 从而使处理能力浪费。In most cases, this prevents the regular expression engine from wasting processing power by trying to match text that nearly matches the regular expression pattern. 但这也可能表示超时间隔设置得太低, 或当前计算机负荷导致总体性能下降。It also could indicate, however, that the timeout interval has been set too low, or that the current machine load has caused an overall degradation in performance.

处理异常的方式取决于异常的原因。How you handle the exception depends on the cause of the exception. 如果发生异常的原因是超时间隔设置得太低或计算机负载过多, 则可以增加超时间隔, 然后重试匹配操作。If the exception occurs because the time-out interval is set too low or because of excessive machine load, you can increase the time-out interval and retry the matching operation. 如果发生异常的原因是正则表达式依赖过多回溯, 则可以假定不存在匹配项, 并且可以选择记录有助于修改正则表达式模式的信息。If the exception occurs because the regular expression relies on excessive backtracking, you can assume that a match does not exist, and, optionally, you can log information that will help you modify the regular expression pattern.

在实例化正则表达式对象时, 可以通过Regex(String, RegexOptions, TimeSpan)调用构造函数来设置超时间隔。You can set a time-out interval by calling the Regex(String, RegexOptions, TimeSpan) constructor when you instantiate a regular expression object. 对于静态方法, 你可以通过调用具有matchTimeout参数的匹配方法的重载来设置超时间隔。For static methods, you can set a time-out interval by calling an overload of a matching method that has a matchTimeout parameter. 如果未显式设置超时值, 则按如下方式确定默认超时值:If you do not set a time-out value explicitly, the default time-out value is determined as follows:

  • 使用应用程序范围的超时值 (如果存在)。By using the application-wide time-out value, if one exists. 这可以是任何应用于在其中Regex实例化对象的应用程序域或进行静态方法调用的超时值。This can be any time-out value that applies to the application domain in which the Regex object is instantiated or the static method call is made. 通过调用AppDomain.SetData方法将TimeSpan值的字符串表示形式分配给 "REGEX_DEFAULT_MATCH_TIMEOUT" 属性, 可以设置应用程序范围的超时值。You can set the application-wide time-out value by calling the AppDomain.SetData method to assign the string representation of a TimeSpan value to the "REGEX_DEFAULT_MATCH_TIMEOUT" property.

  • 如果未设置应用InfiniteMatchTimeout程序范围的超时值, 则使用值。By using the value InfiniteMatchTimeout, if no application-wide time-out value has been set.

重要

建议在所有正则表达式模式匹配操作中设置超时值。We recommend that you set a time-out value in all regular expression pattern-matching operations. 有关详细信息, 请参阅正则表达式的最佳实践For more information, see Best Practices for Regular Expressions.

返回到备注Back to Remarks

构造函数

Regex() Regex() Regex() Regex()

初始化 Regex 类的新实例。Initializes a new instance of the Regex class.

Regex(SerializationInfo, StreamingContext) Regex(SerializationInfo, StreamingContext) Regex(SerializationInfo, StreamingContext) Regex(SerializationInfo, StreamingContext)

使用序列化数据初始化 Regex 类的新实例。Initializes a new instance of the Regex class by using serialized data.

Regex(String) Regex(String) Regex(String) Regex(String)

为指定的正则表达式初始化 Regex 类的新实例。Initializes a new instance of the Regex class for the specified regular expression.

Regex(String, RegexOptions) Regex(String, RegexOptions) Regex(String, RegexOptions) Regex(String, RegexOptions)

使用修改模式的选项为指定的正则表达式初始化 Regex 类的新实例。Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern.

Regex(String, RegexOptions, TimeSpan) Regex(String, RegexOptions, TimeSpan) Regex(String, RegexOptions, TimeSpan) Regex(String, RegexOptions, TimeSpan)

使用修改模式的选项和指定在超时前多久模式匹配方法应进行匹配尝试的值为指定正则表达式初始化 Regex 类的新实例。Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern and a value that specifies how long a pattern matching method should attempt a match before it times out.

字段

capnames capnames capnames capnames

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

caps caps caps caps

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

capsize capsize capsize capsize

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

capslist capslist capslist capslist

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

factory factory factory factory

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

InfiniteMatchTimeout InfiniteMatchTimeout InfiniteMatchTimeout InfiniteMatchTimeout

指定模式匹配操作不应超时。Specifies that a pattern-matching operation should not time out.

internalMatchTimeout internalMatchTimeout internalMatchTimeout internalMatchTimeout

操作超时之前在一个模式匹配操作中可以经过的最长时间。The maximum amount of time that can elapse in a pattern-matching operation before the operation times out.

pattern pattern pattern pattern

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

roptions roptions roptions roptions

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

属性

CacheSize CacheSize CacheSize CacheSize

获取或设置已编译的正则表达式的当前静态缓存中的最大项数。Gets or sets the maximum number of entries in the current static cache of compiled regular expressions.

CapNames CapNames CapNames CapNames

获取或设置将命名捕获组映射到其索引值的字典。Gets or sets a dictionary that maps named capturing groups to their index values.

Caps Caps Caps Caps

获取或设置将编号捕获组映射到其索引值的字典。Gets or sets a dictionary that maps numbered capturing groups to their index values.

MatchTimeout MatchTimeout MatchTimeout MatchTimeout

获取当前实例的超时间隔。Gets the time-out interval of the current instance.

Options Options Options Options

获取传递给 Regex 构造函数的选项。Gets the options that were passed into the Regex constructor.

RightToLeft RightToLeft RightToLeft RightToLeft

获取一个值,该值指示正则表达式是否从右向左进行搜索。Gets a value that indicates whether the regular expression searches from right to left.

方法

CompileToAssembly(RegexCompilationInfo[], AssemblyName) CompileToAssembly(RegexCompilationInfo[], AssemblyName) CompileToAssembly(RegexCompilationInfo[], AssemblyName) CompileToAssembly(RegexCompilationInfo[], AssemblyName)

将一个或多个指定的 Regex 对象编译为命名程序集。Compiles one or more specified Regex objects to a named assembly.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])

将一个或多个指定的 Regex 对象编译为具有指定特性的命名程序集。Compiles one or more specified Regex objects to a named assembly with the specified attributes.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)

将一个或多个指定的 Regex 对象和一个指定的资源文件编译为具有指定特性的命名程序集。Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Escape(String) Escape(String) Escape(String) Escape(String)

通过替换为转义码来转义最小的字符集(\、*、+、?、|、{、[、(、)、^、$、.、# 和空白)。Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $, ., #, and white space) by replacing them with their escape codes. 这将指示正则表达式引擎按原义解释这些字符而不是解释为元字符。This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

Finalize() Finalize() Finalize() Finalize()

此成员替代 Finalize() 且该主题可能包括更完整的文档。This member overrides Finalize(), and more complete documentation might be available in that topic.

允许 Object 在"垃圾回收"回收 Object 之前尝试释放资源并执行其他清理操作。Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

GetGroupNames() GetGroupNames() GetGroupNames() GetGroupNames()

返回正则表达式的捕获组名数组。Returns an array of capturing group names for the regular expression.

GetGroupNumbers() GetGroupNumbers() GetGroupNumbers() GetGroupNumbers()

返回与数组中的组名相对应的捕获组号的数组。Returns an array of capturing group numbers that correspond to group names in an array.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
GroupNameFromNumber(Int32) GroupNameFromNumber(Int32) GroupNameFromNumber(Int32) GroupNameFromNumber(Int32)

获取与指定组号相对应的组名。Gets the group name that corresponds to the specified group number.

GroupNumberFromName(String) GroupNumberFromName(String) GroupNumberFromName(String) GroupNumberFromName(String)

返回与指定组名相对应的组号。Returns the group number that corresponds to the specified group name.

InitializeReferences() InitializeReferences() InitializeReferences() InitializeReferences()

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

IsMatch(String) IsMatch(String) IsMatch(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) IsMatch(String, Int32) IsMatch(String, Int32) 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) IsMatch(String, String) IsMatch(String, String) IsMatch(String, String)

指示所指定的正则表达式在指定的输入字符串中是否找到了匹配项。Indicates whether the specified regular expression finds a match in the specified input string.

IsMatch(String, String, RegexOptions) IsMatch(String, String, RegexOptions) IsMatch(String, String, RegexOptions) 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) IsMatch(String, String, RegexOptions, TimeSpan) IsMatch(String, String, RegexOptions, TimeSpan) 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.

Match(String) Match(String) Match(String) Match(String)

在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

Match(String, Int32) Match(String, Int32) Match(String, Int32) 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, Int32, Int32) Match(String, Int32, Int32) Match(String, Int32, Int32) 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) Match(String, String) Match(String, String) Match(String, String)

在指定的输入字符串中搜索指定的正则表达式的第一个匹配项。Searches the specified input string for the first occurrence of the specified regular expression.

Match(String, String, RegexOptions) Match(String, String, RegexOptions) Match(String, String, RegexOptions) Match(String, String, RegexOptions)

使用指定的匹配选项在输入字符串中搜索指定的正则表达式的第一个匹配项。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.

Match(String, String, RegexOptions, TimeSpan) Match(String, String, RegexOptions, TimeSpan) Match(String, String, RegexOptions, TimeSpan) 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.

Matches(String) Matches(String) Matches(String) Matches(String)

在指定的输入字符串中搜索正则表达式的所有匹配项。Searches the specified input string for all occurrences of a regular expression.

Matches(String, Int32) Matches(String, Int32) Matches(String, Int32) Matches(String, Int32)

从字符串中的指定起始位置开始,在指定的输入字符串中搜索正则表达式的所有匹配项。Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.

Matches(String, String) Matches(String, String) Matches(String, String) Matches(String, String)

在指定的输入字符串中搜索指定的正则表达式的所有匹配项。Searches the specified input string for all occurrences of a specified regular expression.

Matches(String, String, RegexOptions) Matches(String, String, RegexOptions) Matches(String, String, RegexOptions) Matches(String, String, RegexOptions)

使用指定的匹配选项在指定的输入字符串中搜索指定的正则表达式的所有匹配项。Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.

Matches(String, String, RegexOptions, TimeSpan) Matches(String, String, RegexOptions, TimeSpan) Matches(String, String, RegexOptions, TimeSpan) Matches(String, String, RegexOptions, TimeSpan)

使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项。Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32)

在指定的输入字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32)

在指定的输入子字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

Replace(String, String) Replace(String, String) Replace(String, String) Replace(String, String)

在指定的输入字符串内,使用指定的替换字符串替换与某个正则表达式模式匹配的所有的字符串。In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, Int32) Replace(String, String, Int32) Replace(String, String, Int32) Replace(String, String, Int32)

在指定输入字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32)

在指定输入子字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, String, MatchEvaluator, RegexOptions) Replace(String, String, MatchEvaluator, RegexOptions) Replace(String, String, MatchEvaluator, RegexOptions) Replace(String, String, MatchEvaluator, RegexOptions)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 指定的选项将修改匹配操作。Specified options modify the matching operation.

Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有子字符串。In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Replace(String, String, String) Replace(String, String, String) Replace(String, String, String) Replace(String, String, String)

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

Replace(String, String, String, RegexOptions) Replace(String, String, String, RegexOptions) Replace(String, String, String, RegexOptions) Replace(String, String, String, RegexOptions)

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 指定的选项将修改匹配操作。Specified options modify the matching operation.

Replace(String, String, String, RegexOptions, TimeSpan) Replace(String, String, String, RegexOptions, TimeSpan) Replace(String, String, String, RegexOptions, TimeSpan) Replace(String, String, String, RegexOptions, TimeSpan)

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Split(String) Split(String) Split(String) Split(String)

在由 Regex 构造函数指定的正则表达式模式所定义的位置,将输入字符串拆分为子字符串数组。Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

Split(String, Int32) Split(String, Int32) Split(String, Int32) Split(String, Int32)

在由 Regex 构造函数中指定的正则表达式定义的位置,将输入字符串拆分为子字符串数组指定的最大次数。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor.

Split(String, Int32, Int32) Split(String, Int32, Int32) Split(String, Int32, Int32) Split(String, Int32, Int32)

在由 Regex 构造函数中指定的正则表达式定义的位置,将输入字符串拆分为子字符串数组指定的最大次数。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor. 从输入字符串的指定字符位置开始搜索正则表达式模式。The search for the regular expression pattern starts at a specified character position in the input string.

Split(String, String) Split(String, String) Split(String, String) Split(String, String)

在由正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。Splits an input string into an array of substrings at the positions defined by a regular expression pattern.

Split(String, String, RegexOptions) Split(String, String, RegexOptions) Split(String, String, RegexOptions) Split(String, String, RegexOptions)

在由指定正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 指定的选项将修改匹配操作。Specified options modify the matching operation.

Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan)

在由指定正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

ToString() ToString() ToString() ToString()

返回传入 Regex 构造函数的正则表达式模式。Returns the regular expression pattern that was passed into the Regex constructor.

Unescape(String) Unescape(String) Unescape(String) Unescape(String)

转换输入字符串中的任何转义字符。Converts any escaped characters in the input string.

UseOptionC() UseOptionC() UseOptionC() UseOptionC()

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

UseOptionR() UseOptionR() UseOptionR() UseOptionR()

CompileToAssembly 方法生成的 Regex 对象使用。Used by a Regex object generated by the CompileToAssembly method.

ValidateMatchTimeout(TimeSpan) ValidateMatchTimeout(TimeSpan) ValidateMatchTimeout(TimeSpan) ValidateMatchTimeout(TimeSpan)

检查超时间隔是否在可接受的范围内。Checks whether a time-out interval is within an acceptable range.

显式界面实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用所需的数据填充 SerializationInfo 对象来反序列化当前 Regex 对象。Populates a SerializationInfo object with the data necessary to deserialize the current Regex object.

适用于

线程安全性

Regex类是不可变的 (只读), 并且是线程安全的。The Regex class is immutable (read-only) and thread safe. Regex可以在任何线程上创建对象并在线程之间共享。Regex objects can be created on any thread and shared between threads. 有关详细信息, 请参阅线程安全For more information, see Thread Safety.

另请参阅