RegexCompilationInfo 构造函数

定义

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

重载

RegexCompilationInfo(String, RegexOptions, String, String, Boolean)

初始化 RegexCompilationInfo 类的新实例,该类包含有关要在程序集内包括的正则表达式的信息。Initializes a new instance of the RegexCompilationInfo class that contains information about a regular expression to be included in an assembly.

RegexCompilationInfo(String, RegexOptions, String, String, Boolean, TimeSpan)

初始化 RegexCompilationInfo 类的新实例,该类包含有关要在程序集内包括的指定的超时值的信息。Initializes a new instance of the RegexCompilationInfo class that contains information about a regular expression with a specified time-out value to be included in an assembly.

RegexCompilationInfo(String, RegexOptions, String, String, Boolean)

初始化 RegexCompilationInfo 类的新实例,该类包含有关要在程序集内包括的正则表达式的信息。Initializes a new instance of the RegexCompilationInfo class that contains information about a regular expression to be included in an assembly.

public:
 RegexCompilationInfo(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, System::String ^ name, System::String ^ fullnamespace, bool ispublic);
public RegexCompilationInfo (string pattern, System.Text.RegularExpressions.RegexOptions options, string name, string fullnamespace, bool ispublic);
new System.Text.RegularExpressions.RegexCompilationInfo : string * System.Text.RegularExpressions.RegexOptions * string * string * bool -> System.Text.RegularExpressions.RegexCompilationInfo
Public Sub New (pattern As String, options As RegexOptions, name As String, fullnamespace As String, ispublic As Boolean)

参数

pattern
String

要编译的正则表达式。The regular expression to compile.

options
RegexOptions

编译正则表达式时使用的正则表达式选项。The regular expression options to use when compiling the regular expression.

name
String

表示已编译的正则表达式的类型名称。The name of the type that represents the compiled regular expression.

fullnamespace
String

新类型所属的命名空间。The namespace to which the new type belongs.

ispublic
Boolean

若要使所编译的正则表达式对公共可见,则为 true;否则,为 falsetrue to make the compiled regular expression publicly visible; otherwise, false.

异常

nameEmptyname is Empty.

patternnullpattern is null.

- 或 --or- namenullname is null.

- 或 --or- fullnamespacenullfullnamespace is null.

示例

下面的示例在两个步骤中创建并使用已编译的正则表达式。The following example creates and uses a compiled regular expression in two steps.

在第一步中,编译并执行下面的代码示例。In the first step, compile and execute the following code example. 代码示例中的 RegexCompilationInfo 构造函数定义已编译的正则表达式。The RegexCompilationInfo constructor in the code example defines a compiled regular expression. 执行代码的结果是名为 FishRegex 的程序集,其中包含名为 FishRegex的已编译正则表达式类型。The result of executing the code is an assembly named FishRegex.dll that contains a compiled regular expression type named FishRegex.

// This code example demonstrates the RegexCompilationInfo constructor
// and the Regex.CompileToAssembly() method.
// compile: csc genFishRegex.cs

namespace MyApp
{
    using System;
    using System.Reflection;
    using System.Text.RegularExpressions;
    class GenFishRegEx
    {
        public static void Main()
        {
// Pattern = Group matches one or more word characters, 
//           one or more white space characters, 
//           group matches the string "fish".
        string pat = @"(\w+)\s+(fish)";

// Create the compilation information.
// Case-insensitive matching; type name = "FishRegex"; 
// namespace = "MyApp"; type is public.
        RegexCompilationInfo rci = new RegexCompilationInfo(
                    pat, RegexOptions.IgnoreCase, 
                    "FishRegex", "MyApp", true);

// Setup to compile.
        AssemblyName an = new AssemblyName();
        an.Name = "FishRegex";
        RegexCompilationInfo[] rciList = { rci };

// Compile the regular expression.
        Regex.CompileToAssembly(rciList, an);
        }
    }
}
' This code example demonstrates the RegexCompilationInfo constructor
' and the Regex.CompileToAssembly() method.
' compile: csc genFishRegex.cs

Imports System.Reflection
Imports System.Text.RegularExpressions

Class GenFishRegEx
    Public Shared Sub Main() 
        ' Pattern = Group matches one or more word characters, 
        '           one or more white space characters, 
        '           group matches the string "fish".
        Dim pat As String = "(\w+)\s+(fish)"
        
        ' Create the compilation information.
        ' Case-insensitive matching; type name = "FishRegex"; 
        ' namespace = "MyApp"; type is public.
        Dim rci As New RegexCompilationInfo(pat, RegexOptions.IgnoreCase, _
                                            "FishRegex", "MyApp", True)
        
        ' Setup to compile.
        Dim an As New AssemblyName()
        an.Name = "FishRegex"
        Dim rciList As RegexCompilationInfo() = New RegexCompilationInfo() { rci }
        
        ' Compile the regular expression.
        Regex.CompileToAssembly(rciList, an)
    
    End Sub
End Class

在第二步中,使用对 FishRegex 的引用编译下面的代码示例,然后运行生成的可执行文件。In the second step, compile the following code example using a reference to FishRegex.dll, and then run the resulting executable file. 可执行文件通过使用 FishRegex 类型匹配目标字符串,并在目标字符串中显示匹配项、组、捕获组和匹配项的索引位置。The executable file matches a target string by using the FishRegex type, and displays the match, group, capture group, and index position of the matches in the target string.

// This code example demonstrates the RegexCompilationInfo constructor.
// Execute this code example after executing genFishRegex.exe.
// compile: csc /r:FishRegex.dll useFishRegex.cs

namespace MyApp
  {
  using System;
  using System.Reflection;
  using System.Text.RegularExpressions;

  class UseFishRegEx
    {
    public static void Main()
      {
// Match against the following target string.
      string targetString = "One fish two fish red fish blue fish";
      int matchCount = 0;
      FishRegex f = new FishRegex();

// Display the target string.
      Console.WriteLine("\nInput string = \"" + targetString + "\"");

// Display each match, capture group, capture, and match position.
      foreach (Match m in f.Matches(targetString))
    {
    Console.WriteLine("\nMatch(" + (++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);
        }
      }
    }
      }
    }
  }

/*
This code example produces the following results:

Input string = "One fish two fish red fish blue fish"

Match(1)
Group(1) = "One"
Capture(0) = "One", Position = 0
Group(2) = "fish"
Capture(0) = "fish", Position = 4

Match(2)
Group(1) = "two"
Capture(0) = "two", Position = 9
Group(2) = "fish"
Capture(0) = "fish", Position = 13

Match(3)
Group(1) = "red"
Capture(0) = "red", Position = 18
Group(2) = "fish"
Capture(0) = "fish", Position = 22

Match(4)
Group(1) = "blue"
Capture(0) = "blue", Position = 27
Group(2) = "fish"
Capture(0) = "fish", Position = 32

*/
' This code example demonstrates the RegexCompilationInfo constructor.
' Execute this code example after executing genFishRegex.exe.
' compile: vbc /r:FishRegex.dll useFishRegex.vb

Imports System.Reflection
Imports System.Text.RegularExpressions

Class UseFishRegEx
    Public Shared Sub Main() 
        ' Match against the following target string.
        Dim targetString As String = "One fish two fish red fish blue fish"
        Dim matchCount As Integer = 0
        Dim f As New MyApp.FishRegex()
        
        ' Display the target string.
        Console.WriteLine(vbLf & "Input string = """ & targetString & """")
        
        ' Display each match, capture group, capture, and match position.
        Dim m As Match
        For Each m In f.Matches(targetString)
            matchCount = matchCount + 1
            Console.WriteLine(vbLf & "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)
                    System.Console.WriteLine("Capture(" & j & ") = """ & c.ToString() & _
                                             """, Position = " & c.Index)
                Next j
            Next i
        Next m
    End Sub
End Class

'
'This code example produces the following results:
'
'Input string = "One fish two fish red fish blue fish"
'
'Match(1)
'Group(1) = "One"
'Capture(0) = "One", Position = 0
'Group(2) = "fish"
'Capture(0) = "fish", Position = 4
'
'Match(2)
'Group(1) = "two"
'Capture(0) = "two", Position = 9
'Group(2) = "fish"
'Capture(0) = "fish", Position = 13
'
'Match(3)
'Group(1) = "red"
'Capture(0) = "red", Position = 18
'Group(2) = "fish"
'Capture(0) = "fish", Position = 22
'
'Match(4)
'Group(1) = "blue"
'Capture(0) = "blue", Position = 27
'Group(2) = "fish"
'Capture(0) = "fish", Position = 32
'

注解

RegexCompilationInfo(String, RegexOptions, String, String, Boolean) 构造函数的每个参数都直接对应于 RegexCompilationInfo 类的属性。Each parameter of the RegexCompilationInfo(String, RegexOptions, String, String, Boolean) constructor directly corresponds to a property of the RegexCompilationInfo class. 由于所有属性都是可读/写的,因此也可以直接分配其值。Because all properties are read/write, their values can also be assigned directly.

CompileToAssembly 方法将生成一个包含已编译的正则表达式的程序集。The CompileToAssembly method generates an assembly that contains compiled regular expressions. 因此,不应将 Compiled 指定为 options的值之一。Therefore, you should not specify Compiled as one of the values of options.

如果 true``ispublic,则会为已编译的正则表达式类提供公共可访问性。If ispublic is true, the compiled regular expression class is given public accessibility. 也就是说,可以通过在任何程序集中执行的代码对其进行实例化。That is, it can be instantiated from code that executes in any assembly. 如果 false``ispublic,则会为已编译的正则表达式类提供C#internal (在中)或 Friend (Visual Basic)可访问性。If ispublic is false, the compiled regular expression class is given internal (in C#) or Friend (in Visual Basic) accessibility. 也就是说,它只能从与正则表达式类相同的程序集中执行的代码实例化。That is, it can be instantiated only from code that executes in the same assembly as the regular expression class.

调用方说明

此构造函数创建已编译的正则表达式,该表达式使用在其中创建它的应用程序域的默认超时值。This constructor creates a compiled regular expression that uses the default time-out value of the application domain in which it is created. 如果为应用程序域定义了超时值,则已编译的正则表达式将使用值 InfiniteMatchTimeout,这会阻止模式匹配操作超时。建议使用 RegexCompilationInfo(String, RegexOptions, String, String, Boolean, TimeSpan)创建已编译的正则表达式的构造函数,该构造函数可用于设置超时间隔。If a time-out value is defined for the application domain, the compiled regular expression uses the value InfiniteMatchTimeout, which prevents a pattern-matching operation from timing out. The recommended constructor for creating a compiled regular expression is RegexCompilationInfo(String, RegexOptions, String, String, Boolean, TimeSpan), which lets you set the time-out interval.

RegexCompilationInfo(String, RegexOptions, String, String, Boolean, TimeSpan)

初始化 RegexCompilationInfo 类的新实例,该类包含有关要在程序集内包括的指定的超时值的信息。Initializes a new instance of the RegexCompilationInfo class that contains information about a regular expression with a specified time-out value to be included in an assembly.

public:
 RegexCompilationInfo(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, System::String ^ name, System::String ^ fullnamespace, bool ispublic, TimeSpan matchTimeout);
public RegexCompilationInfo (string pattern, System.Text.RegularExpressions.RegexOptions options, string name, string fullnamespace, bool ispublic, TimeSpan matchTimeout);
new System.Text.RegularExpressions.RegexCompilationInfo : string * System.Text.RegularExpressions.RegexOptions * string * string * bool * TimeSpan -> System.Text.RegularExpressions.RegexCompilationInfo
Public Sub New (pattern As String, options As RegexOptions, name As String, fullnamespace As String, ispublic As Boolean, matchTimeout As TimeSpan)

参数

pattern
String

要编译的正则表达式。The regular expression to compile.

options
RegexOptions

编译正则表达式时使用的正则表达式选项。The regular expression options to use when compiling the regular expression.

name
String

表示已编译的正则表达式的类型名称。The name of the type that represents the compiled regular expression.

fullnamespace
String

新类型所属的命名空间。The namespace to which the new type belongs.

ispublic
Boolean

若要使所编译的正则表达式对公共可见,则为 true;否则,为 falsetrue to make the compiled regular expression publicly visible; otherwise, false.

matchTimeout
TimeSpan

正则表达式的默认超时间隔。The default time-out interval for the regular expression.

异常

nameEmptyname is Empty.

patternnullpattern is null.

- 或 --or- namenullname is null.

- 或 --or- fullnamespacenullfullnamespace is null.

matchTimeout 为负、零或大于 24 天左右。matchTimeout is negative, zero, or greater than approximately 24 days.

示例

下面的示例定义了一个名为 DuplicateChars 的、用于标识输入字符串中相同字符的两个或更多匹配项的已编译的正则表达式。The following example defines a single compiled regular expression named DuplicateChars that identifies two or more occurrences of the same character in an input string. 已编译的正则表达式的默认超时值为2秒。The compiled regular expression has a default time-out of 2 seconds. 当您执行该示例时,它将创建一个名为 RegexLib 的类库,其中包含已编译的正则表达式。When you execute the example, it creates a class library named RegexLib.dll that contains the compiled regular expression.

using System;
using System.Reflection;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
        // Match two or more occurrences of the same character.
        string pattern = @"(\w)\1+";
        
        // Use case-insensitive matching. 
        var rci = new RegexCompilationInfo(pattern, RegexOptions.IgnoreCase,
                                           "DuplicateChars", "CustomRegexes", 
                                           true, TimeSpan.FromSeconds(2));

        // Define an assembly to contain the compiled regular expression.
        var an = new AssemblyName();
        an.Name = "RegexLib";
        RegexCompilationInfo[] rciList = { rci };

        // Compile the regular expression and create the assembly.
        Regex.CompileToAssembly(rciList, an);
   }
}
Imports System.Reflection
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
        ' Match two or more occurrences of the same character.
        Dim pattern As String = "(\w)\1+"
        
        ' Use case-insensitive matching. 
        Dim rci As New RegexCompilationInfo(pattern, RegexOptions.IgnoreCase,
                                            "DuplicateChars", "CustomRegexes", 
                                            True, TimeSpan.FromSeconds(2))

        ' Define an assembly to contain the compiled regular expression.
        Dim an As New AssemblyName()
        an.Name = "RegexLib"
        Dim rciList As RegexCompilationInfo() = New RegexCompilationInfo() { rci }

        ' Compile the regular expression and create the assembly.
        Regex.CompileToAssembly(rciList, an)
   End Sub
End Module

正则表达式模式 (\w)\1+ 的定义如下表所示。The regular expression pattern (\w)\1+ is defined as shown in the following table.

模式Pattern 说明Description
(\w) 匹配任意单词字符,并将其分配给第一个捕获组。Match any word character and assign it to the first capturing group.
\1+ 匹配第一个捕获组的值的一个或多个匹配项。Match one or more occurrences of the value of the first captured group.

下面的示例使用 DuplicatedChars 正则表达式来标识字符串数组中的重复字符。The following example uses the DuplicatedChars regular expression to identify duplicate characters in a string array. 当它调用 DuplicatedChars 构造函数时,它会将超时间隔更改为5秒。When it calls the DuplicatedChars constructor, it changes the time-out interval to .5 seconds.

using CustomRegexes;
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      var rgx = new DuplicateChars(TimeSpan.FromSeconds(.5));
      
      string[] values = { "Greeeeeat", "seed", "deed", "beam", 
                          "loop", "Aardvark" };
      // Display regex information.
      Console.WriteLine("Regular Expression Pattern: {0}", rgx);
      Console.WriteLine("Regex timeout value: {0} seconds\n", 
                        rgx.MatchTimeout.TotalSeconds);
      
      // Display matching information.
      foreach (var value in values) {
         Match m = rgx.Match(value);
         if (m.Success)
            Console.WriteLine("'{0}' found in '{1}' at positions {2}-{3}",
                              m.Value, value, m.Index, m.Index + m.Length - 1);
         else
            Console.WriteLine("No match found in '{0}'", value);
      }                                                         
   }
}
// The example displays the following output:
//       Regular Expression Pattern: (\w)\1+
//       Regex timeout value: 0.5 seconds
//       
//       //eeeee// found in //Greeeeeat// at positions 2-6
//       //ee// found in //seed// at positions 1-2
//       //ee// found in //deed// at positions 1-2
//       No match found in //beam//
//       //oo// found in //loop// at positions 1-2
//       //Aa// found in //Aardvark// at positions 0-1
Imports CustomRegexes
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim rgx As New DuplicateChars(TimeSpan.FromSeconds(.5))
      
      Dim values() As String = { "Greeeeeat", "seed", "deed", "beam", 
                                 "loop", "Aardvark" }
      ' Display regex information.
      Console.WriteLine("Regular Expression Pattern: {0}", rgx)
      Console.WriteLine("Regex timeout value: {0} seconds", 
                        rgx.MatchTimeout.TotalSeconds)
      Console.WriteLine()
      
      ' Display matching information.
      For Each value In values
         Dim m As Match = rgx.Match(value)
         If m.Success Then
            Console.WriteLine("'{0}' found in '{1}' at positions {2}-{3}",
                              m.Value, value, m.Index, m.Index + m.Length - 1)
         Else
            Console.WriteLine("No match found in '{0}'", value)
         End If   
      Next                                                         
   End Sub
End Module
' The example displays the following output:
'       Regular Expression Pattern: (\w)\1+
'       Regex timeout value: 0.5 seconds
'       
'       'eeeee' found in 'Greeeeeat' at positions 2-6
'       'ee' found in 'seed' at positions 1-2
'       'ee' found in 'deed' at positions 1-2
'       No match found in 'beam'
'       'oo' found in 'loop' at positions 1-2
'       'Aa' found in 'Aardvark' at positions 0-1

注解

RegexCompilationInfo(String, RegexOptions, String, String, Boolean) 构造函数的每个参数都直接对应于 RegexCompilationInfo 类的属性。Each parameter of the RegexCompilationInfo(String, RegexOptions, String, String, Boolean) constructor directly corresponds to a property of the RegexCompilationInfo class. 由于所有属性都是可读/写的,因此也可以直接分配其值。Because all properties are read/write, their values can also be assigned directly.

CompileToAssembly 方法将生成一个包含已编译的正则表达式的程序集。The CompileToAssembly method generates an assembly that contains compiled regular expressions. 因此,不应将 Compiled 指定为 options的值之一。Therefore, you should not specify Compiled as one of the values of options.

如果 true``ispublic,则会为已编译的正则表达式类提供公共可访问性。If ispublic is true, the compiled regular expression class is given public accessibility. 也就是说,可以通过在任何程序集中执行的代码对其进行实例化。That is, it can be instantiated from code that executes in any assembly. 如果 false``ispublic,则会为已编译的正则表达式类提供C#internal (在中)或 Friend (Visual Basic)可访问性。If ispublic is false, the compiled regular expression class is given internal (in C#) or Friend (in Visual Basic) accessibility. 也就是说,它只能从与正则表达式类相同的程序集中执行的代码实例化。That is, it can be instantiated only from code that executes in the same assembly as the regular expression class.

matchTimeout 参数定义已编译的正则表达式的默认超时间隔。The matchTimeout parameter defines the default time-out interval for the compiled regular expression. 此值表示已编译的正则表达式对象在操作超时之前将执行单个匹配操作的大约时间量,并且正则表达式引擎将在其下一次计时检查过程中引发 RegexMatchTimeoutException 异常。This value represents the approximate amount of time that a compiled regular expression object will execute a single matching operation before the operation times out and the regular expression engine throws a RegexMatchTimeoutException exception during its next timing check. 有关超时值的其他信息,请参阅 "MatchTimeout" 属性。For additional information about the time-out value, see the MatchTimeout property.

重要

建议你始终为已编译的正则表达式设置默认超时值。We recommend that you always set a default time-out value for a compiled regular expression. 正则表达式库的使用者可以通过将表示新的超时间隔的 TimeSpan 值传递到此构造函数重载,来覆盖该超时值。Consumers of your regular expression library can override that time-out value by passing a TimeSpan value that represents the new time-out interval to this constructor overload.

另请参阅

适用于