Regex.CompileToAssembly 메서드

정의

정규식을 컴파일하고 단일 어셈블리의 디스크에 저장합니다.

오버로드

Name Description
CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)
사용되지 않음.

지정된 특성이 있는 명명된 Regex 어셈블리에 지정된 개체와 지정된 리소스 파일을 하나 이상 컴파일합니다.

CompileToAssembly(RegexCompilationInfo[], AssemblyName)
사용되지 않음.

하나 이상의 지정된 개체를 명명된 Regex 어셈블리로 컴파일합니다.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])
사용되지 않음.

지정된 특성을 사용하여 하나 이상의 지정된 Regex 개체를 명명된 어셈블리로 컴파일합니다.

설명

메모

.NET Core 및 .NET 5 이상에서 Regex.CompileToAssembly 메서드에 대한 호출은 PlatformNotSupportedException throw합니다. 어셈블리 작성은 지원되지 않습니다.

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

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

주의

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

지정된 특성이 있는 명명된 Regex 어셈블리에 지정된 개체와 지정된 리소스 파일을 하나 이상 컴파일합니다.

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)

매개 변수

regexinfos
RegexCompilationInfo[]

컴파일할 정규식을 설명하는 배열입니다.

assemblyname
AssemblyName

어셈블리의 파일 이름입니다.

attributes
CustomAttributeBuilder[]

어셈블리에 적용할 특성을 정의하는 배열입니다.

resourceFile
String

어셈블리에 포함할 Win32 리소스 파일의 이름입니다.

특성

예외

매개 변수 assemblyname 속성의 Name 값은 빈 문자열 또는 null 문자열입니다.

-또는-

하나 이상의 개체에 대한 정규식 패턴에 regexinfos 잘못된 구문이 포함되어 있습니다.

assemblyname 또는 regexinfos .입니다 null.

매개 변수는 resourceFile 잘못된 Win32 리소스 파일을 지정합니다.

매개 변수로 지정된 resourceFile 파일을 찾을 수 없습니다.

컴파일된 정규식의 어셈블리 만들기는 지원되지 않습니다.

설명

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 메서드는 regexinfos 배열에 정의된 각 정규식이 클래스로 표현되는 .NET Framework 어셈블리를 생성합니다. 일반적으로 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 메서드는 컴파일된 정규식의 어셈블리를 생성하는 별도의 애플리케이션에서 호출됩니다. 어셈블리에 포함된 각 정규식의 특징은 다음과 같습니다.

  • 클래스에서 Regex 파생됩니다.

  • 해당 fullnamespace 개체의 매개 변수 및 name 매개 변수로 RegexCompilationInfo 정의된 정규화된 이름이 할당됩니다.

  • 기본(또는 매개 변수가 없는) 생성자가 있습니다.

일반적으로 컴파일된 정규식을 인스턴스화하고 사용하는 코드는 어셈블리를 만드는 코드와 별개인 어셈블리 또는 애플리케이션에서 찾을 수 있습니다.

메서드는 특정 언어의 클래스 정의 키워드(예: C#의 또는 )를 사용하는 대신 메서드 호출에서 .NET Framework 어셈블리를 생성하기 때문입니다. )에서는 개발 언어의 표준 특성 구문을 사용하여 .NET Framework 특성을 어셈블리에 할당할 수 없습니다. 매개 변수는 attributes 어셈블리에 적용되는 특성을 정의하기 위한 대체 메서드를 제공합니다. 어셈블리에 적용하려는 각 특성에 대해 다음을 수행합니다.

  1. 호출하려는 특성 생성자의 매개 변수 형식을 나타내는 개체 배열 Type 을 만듭니다.

  2. Type 새 어셈블리에 적용할 특성 클래스를 나타내는 개체를 검색합니다.

  3. GetConstructor 특성 Type 개체의 메서드를 호출하여 ConstructorInfo 호출하려는 특성 생성자를 나타내는 개체를 검색합니다. GetConstructor 생성자의 Type 매개 변수 형식을 나타내는 개체 배열을 메서드에 전달합니다.

  4. 특성의 Object 생성자에 전달할 매개 변수를 정의하는 배열을 만듭니다.

  5. 3단계에서 검색된 개체와 4단계에서 만든 배열을 생성자에 CustomAttributeBuilder 전달하여 개체를 ConstructorInfo 인스턴스화 Object 합니다.

그런 다음 매개 변수 대신 이러한 CustomAttributeBuilder 개체의 배열을 attributes 메서드에 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 전달할 수 있습니다.

호출자 참고

.NET Framework 4.5 또는 해당 지점 릴리스가 설치된 시스템에서 개발하는 경우 .NET Framework 4를 대상으로 하고 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 메서드를 사용하여 컴파일된 정규식을 포함하는 어셈블리를 만듭니다. .NET Framework 4가 있는 시스템에서 해당 어셈블리의 정규식 중 하나를 사용하려고 하면 예외가 throw됩니다. 이 문제를 해결하기 위해서는 다음 중 하나를 수행합니다.

  • 이후 버전이 설치되지 않고 .NET Framework 4가 있는 시스템에서 컴파일된 정규식이 포함된 어셈블리를 빌드합니다.

  • 어셈블리에서 컴파일된 정규식을 호출 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 하고 검색하는 대신 개체를 인스턴스화하거나 정규식 패턴 일치 메서드를 Regex 호출할 때 옵션과 함께 Compiled 정적 또는 인스턴스 Regex 메서드를 사용합니다.

추가 정보

적용 대상

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

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

주의

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

하나 이상의 지정된 개체를 명명된 Regex 어셈블리로 컴파일합니다.

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)

매개 변수

regexinfos
RegexCompilationInfo[]

컴파일할 정규식을 설명하는 배열입니다.

assemblyname
AssemblyName

어셈블리의 파일 이름입니다.

특성

예외

매개 변수 assemblyname 속성의 Name 값은 빈 문자열 또는 null 문자열입니다.

-또는-

하나 이상의 개체에 대한 정규식 패턴에 regexinfos 잘못된 구문이 포함되어 있습니다.

assemblyname 또는 regexinfos .입니다 null.

컴파일된 정규식의 어셈블리 만들기는 지원되지 않습니다.

예제

다음 예제에서는 RegexLib.dll라는 어셈블리를 만듭니다. 어셈블리에는 두 개의 컴파일된 정규식이 포함됩니다. 첫 번째 , Utilities.RegularExpressions.DuplicatedString두 개의 동일한 연속 단어와 일치합니다. 둘째, Utilities.RegularExpressions.EmailAddress문자열의 형식이 전자 메일 주소인지 여부를 확인합니다.

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

그런 다음, 문자열에서 중복 단어를 확인하는 정규식이 인스턴스화되고 다음 예제에서 사용됩니다.

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

이 두 번째 예제를 성공적으로 컴파일하려면 RegexLib.dll(첫 번째 예제에서 만든 어셈블리)에 대한 참조가 프로젝트에 추가되어야 합니다.

설명

CompileToAssembly(RegexCompilationInfo[], AssemblyName) 메서드는 regexinfos 배열에 정의된 각 정규식이 클래스로 표현되는 .NET Framework 어셈블리를 생성합니다. 일반적으로 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 메서드는 컴파일된 정규식의 어셈블리를 생성하는 별도의 애플리케이션에서 호출됩니다. 어셈블리에 포함된 각 정규식의 특징은 다음과 같습니다.

  • 클래스에서 Regex 파생됩니다.

  • 해당 fullnamespace 개체의 매개 변수 및 name 매개 변수로 RegexCompilationInfo 정의된 정규화된 이름이 할당됩니다.

  • 기본(또는 매개 변수가 없는) 생성자가 있습니다.

일반적으로 컴파일된 정규식을 인스턴스화하고 사용하는 코드는 어셈블리를 만드는 코드와 별개인 어셈블리 또는 애플리케이션에서 찾을 수 있습니다.

호출자 참고

.NET Framework 4.5 또는 해당 지점 릴리스가 설치된 시스템에서 개발하는 경우 .NET Framework 4를 대상으로 하고 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 메서드를 사용하여 컴파일된 정규식을 포함하는 어셈블리를 만듭니다. .NET Framework 4가 있는 시스템에서 해당 어셈블리의 정규식 중 하나를 사용하려고 하면 예외가 throw됩니다. 이 문제를 해결하기 위해서는 다음 중 하나를 수행합니다.

  • 이후 버전이 설치되지 않고 .NET Framework 4가 있는 시스템에서 컴파일된 정규식이 포함된 어셈블리를 빌드합니다.

  • 어셈블리에서 컴파일된 정규식을 호출 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 하고 검색하는 대신 개체를 인스턴스화하거나 정규식 패턴 일치 메서드를 Regex 호출할 때 옵션과 함께 Compiled 정적 또는 인스턴스 Regex 메서드를 사용합니다.

추가 정보

적용 대상

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

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

주의

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

지정된 특성을 사용하여 하나 이상의 지정된 Regex 개체를 명명된 어셈블리로 컴파일합니다.

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())

매개 변수

regexinfos
RegexCompilationInfo[]

컴파일할 정규식을 설명하는 배열입니다.

assemblyname
AssemblyName

어셈블리의 파일 이름입니다.

attributes
CustomAttributeBuilder[]

어셈블리에 적용할 특성을 정의하는 배열입니다.

특성

예외

매개 변수 assemblyname 속성의 Name 값은 빈 문자열 또는 null 문자열입니다.

-또는-

하나 이상의 개체에 대한 정규식 패턴에 regexinfos 잘못된 구문이 포함되어 있습니다.

assemblyname 또는 regexinfos .입니다 null.

컴파일된 정규식의 어셈블리 만들기는 지원되지 않습니다.

예제

다음 예제에서는 이름이 RegexLib.dll 어셈블리를 만들고 해당 어셈블리에 AssemblyTitleAttribute 특성을 적용합니다. 어셈블리에는 두 개의 컴파일된 정규식이 포함됩니다. 첫 번째 , Utilities.RegularExpressions.DuplicatedString두 개의 동일한 연속 단어와 일치합니다. 둘째, Utilities.RegularExpressions.EmailAddress문자열의 형식이 전자 메일 주소인지 여부를 확인합니다.

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

ILDasm과 같은 리플렉션 유틸리티를 사용하여 매니페스트를 검사하여 특성이 어셈블리에 적용되었는지 확인할 AssemblyTitleAttribute 수 있습니다.

그런 다음, 문자열에서 중복 단어를 확인하는 정규식이 인스턴스화되고 다음 예제에서 사용됩니다.

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

이 두 번째 예제를 성공적으로 컴파일하려면 RegexLib.dll(첫 번째 예제에서 만든 어셈블리)에 대한 참조가 프로젝트에 추가되어야 합니다.

설명

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 메서드는 regexinfos 배열에 정의된 각 정규식이 클래스로 표현되는 .NET Framework 어셈블리를 생성합니다. 일반적으로 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 메서드는 컴파일된 정규식의 어셈블리를 생성하는 별도의 애플리케이션에서 호출됩니다. 어셈블리에 포함된 각 정규식의 특징은 다음과 같습니다.

  • 클래스에서 Regex 파생됩니다.

  • 해당 fullnamespace 개체의 매개 변수 및 name 매개 변수로 RegexCompilationInfo 정의된 정규화된 이름이 할당됩니다.

  • 기본(또는 매개 변수가 없는) 생성자가 있습니다.

일반적으로 컴파일된 정규식을 인스턴스화하고 사용하는 코드는 어셈블리를 만드는 코드와 별개인 어셈블리 또는 애플리케이션에서 찾을 수 있습니다.

메서드는 특정 언어의 클래스 정의 키워드(예: C#의 또는 )를 사용하는 대신 메서드 호출에서 .NET Framework 어셈블리를 생성하기 때문입니다. )에서는 개발 언어의 표준 특성 구문을 사용하여 .NET Framework 특성을 어셈블리에 할당할 수 없습니다. 매개 변수는 attributes 어셈블리에 적용되는 특성을 정의하기 위한 대체 메서드를 제공합니다. 어셈블리에 적용하려는 각 특성에 대해 다음을 수행합니다.

  1. 호출하려는 특성 생성자의 매개 변수 형식을 나타내는 개체 배열 Type 을 만듭니다.

  2. Type 새 어셈블리에 적용할 특성 클래스를 나타내는 개체를 검색합니다.

  3. GetConstructor 특성 Type 개체의 메서드를 호출하여 ConstructorInfo 호출하려는 특성 생성자를 나타내는 개체를 검색합니다. GetConstructor 생성자의 매개 변수 형식을 나타내는 개체의 배열 Type 을 메서드에 전달합니다.

  4. 특성의 Object 생성자에 전달할 매개 변수를 정의하는 배열을 만듭니다.

  5. 3단계에서 검색된 개체와 4단계에서 만든 배열을 생성자에 CustomAttributeBuilder 전달하여 개체를 ConstructorInfo 인스턴스화 Object 합니다.

그런 다음 매개 변수 대신 이러한 CustomAttributeBuilder 개체의 배열을 attributes 메서드에 Regex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 전달할 수 있습니다.

호출자 참고

.NET Framework 4.5 또는 해당 지점 릴리스가 설치된 시스템에서 개발하는 경우 .NET Framework 4를 대상으로 하고 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 메서드를 사용하여 컴파일된 정규식을 포함하는 어셈블리를 만듭니다. .NET Framework 4가 있는 시스템에서 해당 어셈블리의 정규식 중 하나를 사용하려고 하면 예외가 throw됩니다. 이 문제를 해결하기 위해서는 다음 중 하나를 수행합니다.

  • 이후 버전이 설치되지 않고 .NET Framework 4가 있는 시스템에서 컴파일된 정규식이 포함된 어셈블리를 빌드합니다.

  • 어셈블리에서 컴파일된 정규식을 호출 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 하고 검색하는 대신 개체를 인스턴스화하거나 정규식 패턴 일치 메서드를 Regex 호출할 때 옵션과 함께 Compiled 정적 또는 인스턴스 Regex 메서드를 사용합니다.

추가 정보

적용 대상