Język

Regex.CompileToAssembly Metoda

Definicja

Kompiluje wyrażenia regularne i zapisuje je na dysku w jednym zestawie.

Przeciążenia

Nazwa Opis
CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)
Przestarzałe.

Kompiluje co najmniej jeden określony Regex obiekt i określony plik zasobów do nazwanego zestawu z określonymi atrybutami.

CompileToAssembly(RegexCompilationInfo[], AssemblyName)
Przestarzałe.

Kompiluje co najmniej jeden określony Regex obiekt do nazwanego zestawu.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])
Przestarzałe.

Kompiluje co najmniej jeden określony Regex obiekt do nazwanego zestawu z określonymi atrybutami.

Uwagi

Note

W .NET Core i .NET 5 lub nowszych wywołania metody Regex.CompileToAssembly zgłaszają PlatformNotSupportedException. Zapisywanie zestawu nie jest obsługiwane.

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

Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs

Uwaga

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

Kompiluje co najmniej jeden określony Regex obiekt i określony plik zasobów do nazwanego zestawu z określonymi atrybutami.

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);
[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);
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}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit
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)

Parametry

regexinfos
RegexCompilationInfo[]

Tablica opisując wyrażenia regularne do skompilowania.

assemblyname
AssemblyName

Nazwa pliku zestawu.

attributes
CustomAttributeBuilder[]

Tablica, która definiuje atrybuty, które mają być stosowane do zestawu.

resourceFile
String

Nazwa pliku zasobu Win32 do uwzględnienia w zestawie.

Atrybuty

Wyjątki

Wartość właściwości parametru assemblynameName jest ciągiem pustym lub null.

— lub —

Wzorzec wyrażenia regularnego jednego lub większej liczby obiektów w programie regexinfos zawiera nieprawidłową składnię.

assemblyname lub regexinfos ma wartość null.

Parametr resourceFile wyznacza nieprawidłowy plik zasobu Win32.

Nie można odnaleźć pliku wyznaczonego resourceFile przez parametr .

Tworzenie zestawu skompilowanych wyrażeń regularnych nie jest obsługiwane.

Uwagi

Metoda CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) generuje zestaw .NET Framework, w którym każde wyrażenie regularne zdefiniowane w tablicy regexinfos jest reprezentowane przez klasę. CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) Zazwyczaj metoda jest wywoływana z oddzielnej aplikacji, która generuje zestaw skompilowanych wyrażeń regularnych. Każde wyrażenie regularne zawarte w zestawie ma następujące cechy:

  • Pochodzi ona z Regex klasy .

  • Jest ona przypisana w pełni kwalifikowana nazwa zdefiniowana przez fullnamespace parametry i name odpowiadającego RegexCompilationInfo mu obiektu .

  • Ma on domyślny (lub bez parametrów) konstruktor.

Zazwyczaj kod, który tworzy wystąpienie i używa skompilowanego wyrażenia regularnego, znajduje się w zestawie lub aplikacji, która jest oddzielona od kodu tworzącego zestaw.

Ponieważ metoda CompileToAssembly generuje zestaw .NET Framework z wywołania metody zamiast używać słowa kluczowego definicji klasy określonego języka (na przykład class w języku C# lub Class... End Class w Visual Basic), nie zezwala na przypisywanie atrybutów platformy .NET do zestawu przy użyciu standardowej składni atrybutów języka programowania. Parametr attributes udostępnia alternatywną metodę definiowania atrybutów, które mają zastosowanie do zestawu. Dla każdego atrybutu, który chcesz zastosować do zestawu, wykonaj następujące czynności:

  1. Utwórz tablicę Type obiektów reprezentujących typy parametrów konstruktora atrybutu, który chcesz wywołać.

  2. Pobierz obiekt reprezentujący klasę Type atrybutów, którą chcesz zastosować do nowego zestawu.

  3. Wywołaj metodę GetConstructor obiektu atrybutu Type , aby pobrać ConstructorInfo obiekt reprezentujący konstruktor atrybutu, który chcesz wywołać. Przekaż metodę GetConstructor tablicy Type obiektów reprezentujących typy parametrów konstruktora

  4. Utwórz tablicę Object , która definiuje parametry, które mają zostać przekazane do konstruktora atrybutu.

  5. CustomAttributeBuilder Utwórz wystąpienie obiektu, przekazując jego konstruktora ConstructorInfo obiekt pobrany w kroku 3 i tablicę utworzoną Object w kroku 4.

Następnie można przekazać tablicę tych CustomAttributeBuilder obiektów zamiast parametru attributesCompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) do metody .

Notatki dotyczące wywoływania

Jeśli programujesz w systemie z zainstalowanym programem .NET Framework 4.5 lub jego wydaniami punktów, należy użyć .NET Framework 4 i użyć metody CompileToAssembly(RegexCompilationInfo[], AssemblyName), aby utworzyć zestaw zawierający skompilowane wyrażenia regularne. Próba użycia jednego z wyrażeń regularnych w tym zestawie w systemie, który ma .NET Framework 4 zgłasza wyjątek. Aby obejść ten problem, możesz wykonać jedną z następujących czynności:

  • Skompiluj zestaw zawierający skompilowane wyrażenia regularne w systemie z zainstalowanym programem .NET Framework 4 zamiast nowszych wersji.

  • Zamiast wywoływać CompileToAssembly(RegexCompilationInfo[], AssemblyName) i pobierać skompilowane wyrażenie regularne z zestawu, użyj metod statycznych lub wystąpień z Regex opcją podczas tworzenia Compiled wystąpienia Regex obiektu lub wywoływania metody dopasowywania wzorca wyrażeń regularnych.

Zobacz też

Dotyczy

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs

Uwaga

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

Kompiluje co najmniej jeden określony Regex obiekt do nazwanego zestawu.

public:
 static void CompileToAssembly(cli::array <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);
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}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName)

Parametry

regexinfos
RegexCompilationInfo[]

Tablica opisując wyrażenia regularne do skompilowania.

assemblyname
AssemblyName

Nazwa pliku zestawu.

Atrybuty

Wyjątki

Wartość właściwości parametru assemblynameName jest ciągiem pustym lub null.

— lub —

Wzorzec wyrażenia regularnego jednego lub większej liczby obiektów w programie regexinfos zawiera nieprawidłową składnię.

assemblyname lub regexinfos ma wartość null.

Tworzenie zestawu skompilowanych wyrażeń regularnych nie jest obsługiwane.

Przykłady

Poniższy przykład tworzy zestaw o nazwie RegexLib.dll. Zestaw zawiera dwa skompilowane wyrażenia regularne. Pierwszy, Utilities.RegularExpressions.DuplicatedString, pasuje do dwóch identycznych ciągłych wyrazów. Drugi element , sprawdza, Utilities.RegularExpressions.EmailAddressczy ciąg ma poprawny format, aby był adresem e-mail.

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

Wyrażenie regularne, które sprawdza ciąg pod kątem zduplikowanych wyrazów, jest następnie tworzone i używane w poniższym przykładzie.

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.'

Pomyślna kompilacja tego drugiego przykładu wymaga odwołania do RegexLib.dll (zestawu utworzonego przez pierwszy przykład) do dodania do projektu.

Uwagi

Metoda CompileToAssembly(RegexCompilationInfo[], AssemblyName) generuje zestaw .NET Framework, w którym każde wyrażenie regularne zdefiniowane w tablicy regexinfos jest reprezentowane przez klasę. CompileToAssembly(RegexCompilationInfo[], AssemblyName) Zazwyczaj metoda jest wywoływana z oddzielnej aplikacji, która generuje zestaw skompilowanych wyrażeń regularnych. Każde wyrażenie regularne zawarte w zestawie ma następujące cechy:

  • Pochodzi ona z Regex klasy .

  • Jest ona przypisana w pełni kwalifikowana nazwa zdefiniowana przez fullnamespace parametry i name odpowiadającego RegexCompilationInfo mu obiektu .

  • Ma on domyślny (lub bez parametrów) konstruktor.

Zazwyczaj kod, który tworzy wystąpienie i używa skompilowanego wyrażenia regularnego, znajduje się w zestawie lub aplikacji, która jest oddzielona od kodu tworzącego zestaw.

Notatki dotyczące wywoływania

Jeśli programujesz w systemie z zainstalowanym programem .NET Framework 4.5 lub jego wydaniami punktów, należy użyć .NET Framework 4 i użyć metody CompileToAssembly(RegexCompilationInfo[], AssemblyName), aby utworzyć zestaw zawierający skompilowane wyrażenia regularne. Próba użycia jednego z wyrażeń regularnych w tym zestawie w systemie, który ma .NET Framework 4 zgłasza wyjątek. Aby obejść ten problem, możesz wykonać jedną z następujących czynności:

  • Skompiluj zestaw zawierający skompilowane wyrażenia regularne w systemie z zainstalowanym programem .NET Framework 4 zamiast nowszych wersji.

  • Zamiast wywoływać CompileToAssembly(RegexCompilationInfo[], AssemblyName) i pobierać skompilowane wyrażenie regularne z zestawu, użyj metod statycznych lub wystąpień z Regex opcją podczas tworzenia Compiled wystąpienia Regex obiektu lub wywoływania metody dopasowywania wzorca wyrażeń regularnych.

Zobacz też

Dotyczy

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

Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs
Źródło:
Regex.cs

Uwaga

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

Kompiluje co najmniej jeden określony Regex obiekt do nazwanego zestawu z określonymi atrybutami.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <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);
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}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit
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())

Parametry

regexinfos
RegexCompilationInfo[]

Tablica opisując wyrażenia regularne do skompilowania.

assemblyname
AssemblyName

Nazwa pliku zestawu.

attributes
CustomAttributeBuilder[]

Tablica, która definiuje atrybuty, które mają być stosowane do zestawu.

Atrybuty

Wyjątki

Wartość właściwości parametru assemblynameName jest ciągiem pustym lub null.

— lub —

Wzorzec wyrażenia regularnego jednego lub większej liczby obiektów w programie regexinfos zawiera nieprawidłową składnię.

assemblyname lub regexinfos ma wartość null.

Tworzenie zestawu skompilowanych wyrażeń regularnych nie jest obsługiwane.

Przykłady

Poniższy przykład tworzy zestaw o nazwie RegexLib.dll i stosuje AssemblyTitleAttribute do niego atrybut. Zestaw zawiera dwa skompilowane wyrażenia regularne. Pierwszy, Utilities.RegularExpressions.DuplicatedString, pasuje do dwóch identycznych ciągłych wyrazów. Drugi element , sprawdza, Utilities.RegularExpressions.EmailAddressczy ciąg ma poprawny format, aby był adresem e-mail.

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

Możesz sprawdzić, czy AssemblyTitleAttribute atrybut został zastosowany do zestawu, sprawdzając jego manifest za pomocą narzędzia odbicia, takiego jak ILDasm.

Wyrażenie regularne, które sprawdza ciąg pod kątem zduplikowanych wyrazów, jest następnie tworzone i używane w poniższym przykładzie.

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.'

Pomyślna kompilacja tego drugiego przykładu wymaga odwołania do RegexLib.dll (zestawu utworzonego przez pierwszy przykład) do dodania do projektu.

Uwagi

Metoda CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) generuje zestaw .NET Framework, w którym każde wyrażenie regularne zdefiniowane w tablicy regexinfos jest reprezentowane przez klasę. CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) Zazwyczaj metoda jest wywoływana z oddzielnej aplikacji, która generuje zestaw skompilowanych wyrażeń regularnych. Każde wyrażenie regularne zawarte w zestawie ma następujące cechy:

  • Pochodzi ona z Regex klasy .

  • Jest ona przypisana w pełni kwalifikowana nazwa zdefiniowana przez fullnamespace parametry i name odpowiadającego RegexCompilationInfo mu obiektu .

  • Ma on domyślny (lub bez parametrów) konstruktor.

Zazwyczaj kod, który tworzy wystąpienie i używa skompilowanego wyrażenia regularnego, znajduje się w zestawie lub aplikacji, która jest oddzielona od kodu tworzącego zestaw.

Ponieważ metoda CompileToAssembly generuje zestaw .NET Framework z wywołania metody zamiast używać słowa kluczowego definicji klasy określonego języka (na przykład class w języku C# lub Class... End Class w Visual Basic), nie zezwala na przypisywanie atrybutów platformy .NET do zestawu przy użyciu standardowej składni atrybutów języka programowania. Parametr attributes udostępnia alternatywną metodę definiowania atrybutów, które mają zastosowanie do zestawu. Dla każdego atrybutu, który chcesz zastosować do zestawu, wykonaj następujące czynności:

  1. Utwórz tablicę Type obiektów reprezentujących typy parametrów konstruktora atrybutu, który chcesz wywołać.

  2. Pobierz obiekt reprezentujący klasę Type atrybutów, którą chcesz zastosować do nowego zestawu.

  3. Wywołaj metodę GetConstructor obiektu atrybutu Type , aby pobrać ConstructorInfo obiekt reprezentujący konstruktor atrybutu, który chcesz wywołać. Przekaż metodę GetConstructor tablicy Type obiektów reprezentujących typy parametrów konstruktora.

  4. Utwórz tablicę Object , która definiuje parametry, które mają zostać przekazane do konstruktora atrybutu.

  5. CustomAttributeBuilder Utwórz wystąpienie obiektu, przekazując jego konstruktora ConstructorInfo obiekt pobrany w kroku 3 i tablicę utworzoną Object w kroku 4.

Następnie można przekazać tablicę tych CustomAttributeBuilder obiektów zamiast parametru attributesRegex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) do metody .

Notatki dotyczące wywoływania

Jeśli programujesz w systemie z zainstalowanym programem .NET Framework 4.5 lub jego wydaniami punktów, należy użyć .NET Framework 4 i użyć metody CompileToAssembly(RegexCompilationInfo[], AssemblyName), aby utworzyć zestaw zawierający skompilowane wyrażenia regularne. Próba użycia jednego z wyrażeń regularnych w tym zestawie w systemie, który ma .NET Framework 4 zgłasza wyjątek. Aby obejść ten problem, możesz wykonać jedną z następujących czynności:

  • Skompiluj zestaw zawierający skompilowane wyrażenia regularne w systemie z zainstalowanym programem .NET Framework 4 zamiast nowszych wersji.

  • Zamiast wywoływać CompileToAssembly(RegexCompilationInfo[], AssemblyName) i pobierać skompilowane wyrażenie regularne z zestawu, użyj metod statycznych lub wystąpień z Regex opcją podczas tworzenia Compiled wystąpienia Regex obiektu lub wywoływania metody dopasowywania wzorca wyrażeń regularnych.

Zobacz też

Dotyczy