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. 命名此捕获的组wordName this captured group word.
\s+ 匹配一个或多个空白字符。Match one or more white-space characters.
(\k<word>) 与名为的捕获的组匹配wordMatch 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
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.CurrencyDecimalSeparatorCurrencyDecimalDigitsNumberFormatInfo.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.

因为动态生成正则表达式在此示例中,我们不知道在设计时是否当前区域性的货币符号、 十进制符号或正和负号可能会错误地解释为正则正则表达式引擎表达式语言运算符。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. 也有大量的正则表达式模式,例如在一个联机库常规 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

正则表达式 vs。字符串方法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.ContainsString.EndsWith,并String.StartsWith方法确定字符串实例是否包含指定的子字符串; 并String.IndexOfString.IndexOfAnyString.LastIndexOf,和String.LastIndexOfAny方法返回的起始一个字符串中指定的子字符串的位置。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对象是不可变; 当您实例化Regex对象在正则表达式对象的正则表达式不能更改。A 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.5,可以定义超时间隔的正则表达式匹配项。Starting 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.

另请参阅