Breyta

Deila með


Regex.CompileToAssembly Method

Definition

Compiles regular expressions and saves them to disk in a single assembly.

Overloads

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

Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.

CompileToAssembly(RegexCompilationInfo[], AssemblyName)
Obsolete.

Compiles one or more specified Regex objects to a named assembly.

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

Compiles one or more specified Regex objects to a named assembly with the specified attributes.

Remarks

Note

On .NET Core and .NET 5+, calls to the Regex.CompileToAssembly method throw a PlatformNotSupportedException. Writing out an assembly is not supported.

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

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

Caution

Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.

Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <System::Reflection::Emit::CustomAttributeBuilder ^> ^ attributes, System::String ^ resourceFile);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes, string? resourceFile);
[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes, string? resourceFile);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit
[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder(), resourceFile As String)

Parameters

regexinfos
RegexCompilationInfo[]

An array that describes the regular expressions to compile.

assemblyname
AssemblyName

The file name of the assembly.

attributes
CustomAttributeBuilder[]

An array that defines the attributes to apply to the assembly.

resourceFile
String

The name of the Win32 resource file to include in the assembly.

Attributes

Exceptions

The value of the assemblyname parameter's Name property is an empty or null string.

-or-

The regular expression pattern of one or more objects in regexinfos contains invalid syntax.

assemblyname or regexinfos is null.

The resourceFile parameter designates an invalid Win32 resource file.

The file designated by the resourceFile parameter cannot be found.

.NET Core and .NET 5+ only: Creating an assembly of compiled regular expressions is not supported.

Remarks

The CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. Typically, the CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) method is called from a separate application that generates an assembly of compiled regular expressions. Each regular expression included in the assembly has the following characteristics:

  • It is derived from the Regex class.

  • It is assigned the fully qualified name that is defined by the fullnamespace and name parameters of its corresponding RegexCompilationInfo object.

  • It has a default (or parameterless) constructor.

Ordinarily, the code that instantiates and uses the compiled regular expression is found in an assembly or application that is separate from the code that creates the assembly.

Because the CompileToAssembly method generates a .NET Framework assembly from a method call instead of using a particular language's class definition keyword (such as class in C# or Class...End Class in Visual Basic), it does not allow .NET Framework attributes to be assigned to the assembly by using the development language's standard attribute syntax. The attributes parameter provides an alternative method for defining the attributes that apply to the assembly. For each attribute that you want to apply to the assembly, do the following:

  1. Create an array of Type objects representing the parameter types of the attribute constructor that you want to call.

  2. Retrieve a Type object representing the attribute class that you want to apply to the new assembly.

  3. Call the GetConstructor method of the attribute Type object to retrieve a ConstructorInfo object representing the attribute constructor that you want to call. Pass the GetConstructor method the array of Type objects that represents the constructor's parameter types

  4. Create a Object array that defines the parameters to pass to the attribute's constructor.

  5. Instantiate a CustomAttributeBuilder object by passing its constructor the ConstructorInfo object retrieved in step 3 and the Object array created in step 4.

You can then pass an array of these CustomAttributeBuilder objects instead of the attributes parameter to the CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) method.

Notes to Callers

If you are developing on a system that has .NET Framework 4.5 or its point releases installed, you target .NET Framework 4, and you use the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method to create an assembly that contains compiled regular expressions. Trying to use one of the regular expressions in that assembly on a system that has .NET Framework 4 throws an exception. To work around this problem, you can do either of the following:

  • Build the assembly that contains the compiled regular expressions on a system that has .NET Framework 4 instead of later versions installed.

  • Instead of calling CompileToAssembly(RegexCompilationInfo[], AssemblyName) and retrieving the compiled regular expression from an assembly, use either static or instance Regex methods with the Compiled option when you instantiate a Regex object or call a regular expression pattern matching method.

See also

Applies to

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

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

Caution

Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.

Compiles one or more specified Regex objects to a named assembly.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname);
[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName)

Parameters

regexinfos
RegexCompilationInfo[]

An array that describes the regular expressions to compile.

assemblyname
AssemblyName

The file name of the assembly.

Attributes

Exceptions

The value of the assemblyname parameter's Name property is an empty or null string.

-or-

The regular expression pattern of one or more objects in regexinfos contains invalid syntax.

assemblyname or regexinfos is null.

.NET Core and .NET 5+ only: Creating an assembly of compiled regular expressions is not supported.

Examples

The following example creates an assembly named RegexLib.dll. The assembly includes two compiled regular expressions. The first, Utilities.RegularExpressions.DuplicatedString, matches two identical contiguous words. The second, Utilities.RegularExpressions.EmailAddress, checks whether a string has the correct format to be an email address.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;

public class RegexCompilationTest
{
   public static void Main()
   {
      RegexCompilationInfo expr;
      List<RegexCompilationInfo> compilationList = new List<RegexCompilationInfo>();

      // Define regular expression to detect duplicate words
      expr = new RegexCompilationInfo(@"\b(?<word>\w+)\s+(\k<word>)\b", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "DuplicatedString", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);

      // Define regular expression to validate format of email address
      expr = new RegexCompilationInfo(@"^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + 
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "EmailAddress", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);
                                             
      // Generate assembly with compiled regular expressions
      RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
      AssemblyName assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");
      compilationList.CopyTo(compilationArray); 
      Regex.CompileToAssembly(compilationArray, assemName);                                                 
   }
}
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Text.RegularExpressions

Module RegexCompilationTest
   Public Sub Main()
      Dim expr As RegexCompilationInfo
      Dim compilationList As New List(Of RegexCompilationInfo)
          
      ' Define regular expression to detect duplicate words
      expr = New RegexCompilationInfo("\b(?<word>\w+)\s+(\k<word>)\b", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "DuplicatedString", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)

      ' Define regular expression to validate format of email address
      expr = New RegexCompilationInfo("^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + _
                 "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "EmailAddress", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)
                                             
      ' Generate assembly with compiled regular expressions
      Dim compilationArray(compilationList.Count - 1) As RegexCompilationInfo
      Dim assemName As New AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null")
      compilationList.CopyTo(compilationArray) 
      Regex.CompileToAssembly(compilationArray, assemName)                                                 
   End Sub
End Module

The regular expression that checks a string for duplicate words is then instantiated and used by the following example.

using System;
using Utilities.RegularExpressions;

public class CompiledRegexUsage
{
   public static void Main()
   {
      string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
      DuplicatedString duplicateRegex = new DuplicatedString(); 
      if (duplicateRegex.Matches(text).Count > 0)
         Console.WriteLine("There are {0} duplicate words in \n   '{1}'", 
            duplicateRegex.Matches(text).Count, text);
      else
         Console.WriteLine("There are no duplicate words in \n   '{0}'", 
                           text);
   }
}
// The example displays the following output to the console:
//    There are 3 duplicate words in
//       'The the quick brown fox  fox jumps over the lazy dog dog.'
Imports Utilities.RegularExpressions

Module CompiledRegexUsage
   Public Sub Main()
      Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
      Dim duplicateRegex As New DuplicatedString()
      If duplicateRegex.Matches(text).Count > 0 Then
         Console.WriteLine("There are {0} duplicate words in {2}   '{1}'", _
            duplicateRegex.Matches(text).Count, text, vbCrLf)
      Else
         Console.WriteLine("There are no duplicate words in {1}   '{0}'", _
                           text, vbCrLf)
      End If
   End Sub
End Module
' The example displays the following output to the console:
'    There are 3 duplicate words in
'       'The the quick brown fox  fox jumps over the lazy dog dog.'

Successful compilation of this second example requires a reference to RegexLib.dll (the assembly created by the first example) to be added to the project.

Remarks

The CompileToAssembly(RegexCompilationInfo[], AssemblyName) method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. Typically, the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method is called from a separate application that generates an assembly of compiled regular expressions. Each regular expression included in the assembly has the following characteristics:

  • It is derived from the Regex class.

  • It is assigned the fully qualified name that is defined by the fullnamespace and name parameters of its corresponding RegexCompilationInfo object.

  • It has a default (or parameterless) constructor.

Ordinarily, the code that instantiates and uses the compiled regular expression is found in an assembly or application that is separate from the code that creates the assembly.

Notes to Callers

If you are developing on a system that has .NET Framework 4.5 or its point releases installed, you target .NET Framework 4, and you use the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method to create an assembly that contains compiled regular expressions. Trying to use one of the regular expressions in that assembly on a system that has .NET Framework 4 throws an exception. To work around this problem, you can do either of the following:

  • Build the assembly that contains the compiled regular expressions on a system that has .NET Framework 4 instead of later versions installed.

  • Instead of calling CompileToAssembly(RegexCompilationInfo[], AssemblyName) and retrieving the compiled regular expression from an assembly, use either static or instance Regex methods with the Compiled option when you instantiate a Regex object or call a regular expression pattern matching method.

See also

Applies to

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

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

Caution

Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.

Compiles one or more specified Regex objects to a named assembly with the specified attributes.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <System::Reflection::Emit::CustomAttributeBuilder ^> ^ attributes);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes);
[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit
[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder())

Parameters

regexinfos
RegexCompilationInfo[]

An array that describes the regular expressions to compile.

assemblyname
AssemblyName

The file name of the assembly.

attributes
CustomAttributeBuilder[]

An array that defines the attributes to apply to the assembly.

Attributes

Exceptions

The value of the assemblyname parameter's Name property is an empty or null string.

-or-

The regular expression pattern of one or more objects in regexinfos contains invalid syntax.

assemblyname or regexinfos is null.

.NET Core and .NET 5+ only: Creating an assembly of compiled regular expressions is not supported.

Examples

The following example creates an assembly named RegexLib.dll and applies the AssemblyTitleAttribute attribute to it. The assembly includes two compiled regular expressions. The first, Utilities.RegularExpressions.DuplicatedString, matches two identical contiguous words. The second, Utilities.RegularExpressions.EmailAddress, checks whether a string has the correct format to be an email address.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;

public class RegexCompilationTest
{
   public static void Main()
   {
      RegexCompilationInfo expr;
      List<RegexCompilationInfo> compilationList = new List<RegexCompilationInfo>();

      // Define regular expression to detect duplicate words
      expr = new RegexCompilationInfo(@"\b(?<word>\w+)\s+(\k<word>)\b", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "DuplicatedString", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);

      // Define regular expression to validate format of email address
      expr = new RegexCompilationInfo(@"^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + 
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[zA-Z]{2,6}))$", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "EmailAddress", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);
                                             
      // Apply AssemblyTitle attribute to the new assembly
      //
      // Define the parameter(s) of the AssemblyTitle attribute's constructor 
      Type[] parameters = { typeof(string) };
      // Define the assembly's title
      object[] paramValues = { "General-purpose library of compiled regular expressions" };
      // Get the ConstructorInfo object representing the attribute's constructor
      ConstructorInfo ctor = typeof(System.Reflection.AssemblyTitleAttribute).GetConstructor(parameters);
      // Create the CustomAttributeBuilder object array
      CustomAttributeBuilder[] attBuilder = { new CustomAttributeBuilder(ctor, paramValues) }; 
                                                         
      // Generate assembly with compiled regular expressions
      RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
      AssemblyName assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");
      compilationList.CopyTo(compilationArray); 
      Regex.CompileToAssembly(compilationArray, assemName, attBuilder);                                                 
   }
}
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Text.RegularExpressions

Module RegexCompilationTest
   Public Sub Main()
      Dim expr As RegexCompilationInfo
      Dim compilationList As New List(Of RegexCompilationInfo)
          
      ' Define regular expression to detect duplicate words
      expr = New RegexCompilationInfo("\b(?<word>\w+)\s+(\k<word>)\b", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "DuplicatedString", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)

      ' Define regular expression to validate format of email address
      expr = New RegexCompilationInfo("^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + _ 
                 "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "EmailAddress", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)

      ' Apply AssemblyTitle attribute to the new assembly
      '
      ' Define the parameter(s) of the AssemblyTitle attribute's constructor 
      Dim params() As Type = { GetType(String) }
      ' Define the assembly's title
      Dim paramValues() As Object = { "General-purpose library of compiled regular expressions" }
      ' Get the ConstructorInfo object representing the attribute's constructor
      Dim ctor As ConstructorInfo = GetType(System.Reflection.AssemblyTitleAttribute).GetConstructor(params)
      ' Create the CustomAttributeBuilder object array
      Dim attBuilder() As CustomAttributeBuilder = { New CustomAttributeBuilder(ctor, paramValues) } 
                                                         
      ' Generate assembly with compiled regular expressions
      Dim compilationArray(compilationList.Count - 1) As RegexCompilationInfo
      Dim assemName As New AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null")
      compilationList.CopyTo(compilationArray) 
      Regex.CompileToAssembly(compilationArray, assemName, attBuilder) 
   End Sub
End Module

You can verify that the AssemblyTitleAttribute attribute has been applied to the assembly by examining its manifest with a reflection utility such as ILDasm.

The regular expression that checks a string for duplicate words is then instantiated and used by the following example.

using System;
using Utilities.RegularExpressions;

public class CompiledRegexUsage
{
   public static void Main()
   {
      string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
      DuplicatedString duplicateRegex = new DuplicatedString(); 
      if (duplicateRegex.Matches(text).Count > 0)
         Console.WriteLine("There are {0} duplicate words in \n   '{1}'", 
            duplicateRegex.Matches(text).Count, text);
      else
         Console.WriteLine("There are no duplicate words in \n   '{0}'", 
                           text);
   }
}
// The example displays the following output to the console:
//    There are 3 duplicate words in
//       'The the quick brown fox  fox jumps over the lazy dog dog.'
Imports Utilities.RegularExpressions

Module CompiledRegexUsage
   Public Sub Main()
      Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
      Dim duplicateRegex As New DuplicatedString()
      If duplicateRegex.Matches(text).Count > 0 Then
         Console.WriteLine("There are {0} duplicate words in {2}   '{1}'", _
            duplicateRegex.Matches(text).Count, text, vbCrLf)
      Else
         Console.WriteLine("There are no duplicate words in {1}   '{0}'", _
                           text, vbCrLf)
      End If
   End Sub
End Module
' The example displays the following output to the console:
'    There are 3 duplicate words in
'       'The the quick brown fox  fox jumps over the lazy dog dog.'

Successful compilation of this second example requires a reference to RegexLib.dll (the assembly created by the first example) to be added to the project.

Remarks

The CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. Typically, the CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) method is called from a separate application that generates an assembly of compiled regular expressions. Each regular expression included in the assembly has the following characteristics:

  • It is derived from the Regex class.

  • It is assigned the fully qualified name that is defined by the fullnamespace and name parameters of its corresponding RegexCompilationInfo object.

  • It has a default (or parameterless) constructor.

Ordinarily, the code that instantiates and uses the compiled regular expression is found in an assembly or application that is separate from the code that creates the assembly.

Because the CompileToAssembly method generates a .NET Framework assembly from a method call instead of using a particular language's class definition keyword (such as class in C# or Class...End Class in Visual Basic), it does not allow .NET Framework attributes to be assigned to the assembly by using the development language's standard attribute syntax. The attributes parameter provides an alternative method for defining the attributes that apply to the assembly. For each attribute that you want to apply to the assembly, do the following:

  1. Create an array of Type objects representing the parameter types of the attribute constructor that you want to call.

  2. Retrieve a Type object representing the attribute class that you want to apply to the new assembly.

  3. Call the GetConstructor method of the attribute Type object to retrieve a ConstructorInfo object representing the attribute constructor that you want to call. Pass the GetConstructor method the array of Type objects that represents the constructor's parameter types.

  4. Create a Object array that defines the parameters to pass to the attribute's constructor.

  5. Instantiate a CustomAttributeBuilder object by passing its constructor the ConstructorInfo object retrieved in step 3 and the Object array created in step 4.

You can then pass an array of these CustomAttributeBuilder objects instead of the attributes parameter to the Regex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) method.

Notes to Callers

If you are developing on a system that has .NET Framework 4.5 or its point releases installed, you target .NET Framework 4, and you use the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method to create an assembly that contains compiled regular expressions. Trying to use one of the regular expressions in that assembly on a system that has .NET Framework 4 throws an exception. To work around this problem, you can do either of the following:

  • Build the assembly that contains the compiled regular expressions on a system that has .NET Framework 4 instead of later versions installed.

  • Instead of calling CompileToAssembly(RegexCompilationInfo[], AssemblyName) and retrieving the compiled regular expression from an assembly, use either static or instance Regex methods with the Compiled option when you instantiate a Regex object or call a regular expression pattern matching method.

See also

Applies to