Bagikan melalui


RegexCompilationInfo Konstruktor

Definisi

Menginisialisasi instans baru kelas RegexCompilationInfo.

Overload

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

Menginisialisasi instans RegexCompilationInfo baru kelas yang berisi informasi tentang ekspresi reguler yang akan disertakan dalam perakitan.

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

Menginisialisasi instans RegexCompilationInfo baru kelas yang berisi informasi tentang ekspresi reguler dengan nilai batas waktu tertentu untuk disertakan dalam perakitan.

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

Sumber:
RegexCompilationInfo.cs
Sumber:
RegexCompilationInfo.cs
Sumber:
RegexCompilationInfo.cs

Menginisialisasi instans RegexCompilationInfo baru kelas yang berisi informasi tentang ekspresi reguler yang akan disertakan dalam perakitan.

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)

Parameter

pattern
String

Ekspresi reguler untuk dikompilasi.

options
RegexOptions

Opsi ekspresi reguler untuk digunakan saat mengkompilasi ekspresi reguler.

name
String

Nama jenis yang mewakili ekspresi reguler yang dikompilasi.

fullnamespace
String

Namespace tempat tipe baru berada.

ispublic
Boolean

true untuk membuat ekspresi reguler yang dikompilasi terlihat secara publik; jika tidak, false.

Pengecualian

nameadalah Empty.

patternadalah null.

-atau-

nameadalah null.

-atau-

fullnamespaceadalah null.

Contoh

Contoh berikut membuat dan menggunakan ekspresi reguler yang dikompilasi dalam dua langkah.

Pada langkah pertama, kompilasi dan jalankan contoh kode berikut. Konstruktor RegexCompilationInfo dalam contoh kode menentukan ekspresi reguler yang dikompilasi. Hasil dari menjalankan kode adalah rakitan bernama FishRegex.dll yang berisi jenis ekspresi reguler yang dikompilasi bernama 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

Pada langkah kedua, kompilasi contoh kode berikut menggunakan referensi ke FishRegex.dll, lalu jalankan file yang dapat dieksekusi yang dihasilkan. File yang dapat dieksekusi cocok dengan string target dengan menggunakan FishRegex jenis , dan menampilkan kecocokan, grup, grup pengambilan, dan posisi indeks kecocokan dalam string target.

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

Keterangan

Setiap parameter RegexCompilationInfo(String, RegexOptions, String, String, Boolean) konstruktor secara langsung sesuai dengan properti RegexCompilationInfo kelas. Karena semua properti bersifat baca/tulis, nilainya juga dapat ditetapkan secara langsung.

Metode ini CompileToAssembly menghasilkan rakitan yang berisi ekspresi reguler yang dikompilasi. Oleh karena itu, Anda tidak boleh menentukan Compiled sebagai salah satu nilai options.

Jika ispublic adalah true, kelas ekspresi reguler yang dikompilasi diberikan aksesibilitas publik. Artinya, itu dapat diinstansiasi dari kode yang dijalankan di perakitan apa pun. Jika ispublic adalah false, kelas ekspresi reguler yang dikompilasi diberikan internal (dalam C#) atau Friend (dalam Visual Basic) aksesibilitas. Artinya, itu hanya dapat diinstansiasi dari kode yang dijalankan dalam rakitan yang sama dengan kelas ekspresi reguler.

Catatan Bagi Pemanggil

Konstruktor ini membuat ekspresi reguler yang dikompilasi yang menggunakan nilai batas waktu default domain aplikasi tempatnya dibuat. Jika nilai waktu habis ditentukan untuk domain aplikasi, ekspresi reguler yang dikompilasi menggunakan nilai InfiniteMatchTimeout, yang mencegah operasi pencocokan pola kehabisan waktu. Konstruktor yang direkomendasikan untuk membuat ekspresi reguler yang dikompilasi adalah RegexCompilationInfo(String, RegexOptions, String, String, Boolean, TimeSpan), yang memungkinkan Anda mengatur interval waktu habis.

Berlaku untuk

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

Sumber:
RegexCompilationInfo.cs
Sumber:
RegexCompilationInfo.cs
Sumber:
RegexCompilationInfo.cs

Menginisialisasi instans RegexCompilationInfo baru kelas yang berisi informasi tentang ekspresi reguler dengan nilai batas waktu tertentu untuk disertakan dalam perakitan.

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)

Parameter

pattern
String

Ekspresi reguler untuk dikompilasi.

options
RegexOptions

Opsi ekspresi reguler untuk digunakan saat mengkompilasi ekspresi reguler.

name
String

Nama jenis yang mewakili ekspresi reguler yang dikompilasi.

fullnamespace
String

Namespace tempat tipe baru berada.

ispublic
Boolean

true untuk membuat ekspresi reguler yang dikompilasi terlihat secara publik; jika tidak, false.

matchTimeout
TimeSpan

Interval waktu habis default untuk ekspresi reguler.

Pengecualian

nameadalah Empty.

patternadalah null.

-atau-

nameadalah null.

-atau-

fullnamespaceadalah null.

matchTimeout negatif, nol, atau lebih besar dari sekitar 24 hari.

Contoh

Contoh berikut mendefinisikan satu ekspresi reguler yang dikompilasi bernama DuplicateChars yang mengidentifikasi dua atau lebih kemunculan karakter yang sama dalam string input. Ekspresi reguler yang dikompilasi memiliki waktu habis default 2 detik. Saat Anda menjalankan contoh, itu membuat pustaka kelas bernama RegexLib.dll yang berisi ekspresi reguler yang dikompilasi.

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

Pola regex (\w)\1+ didefinisikan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
(\w) Cocokkan karakter kata apa pun dan tetapkan ke grup penangkapan pertama.
\1+ Cocokkan satu atau beberapa kemunculan nilai grup pertama yang diambil.

Contoh berikut menggunakan DuplicatedChars ekspresi reguler untuk mengidentifikasi karakter duplikat dalam array string. Ketika memanggil DuplicatedChars konstruktor, itu mengubah interval waktu habis menjadi .5 detik.

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

Keterangan

Setiap parameter RegexCompilationInfo(String, RegexOptions, String, String, Boolean) konstruktor secara langsung sesuai dengan properti RegexCompilationInfo kelas. Karena semua properti bersifat baca/tulis, nilainya juga dapat ditetapkan secara langsung.

Metode ini CompileToAssembly menghasilkan rakitan yang berisi ekspresi reguler yang dikompilasi. Oleh karena itu, Anda tidak boleh menentukan Compiled sebagai salah satu nilai options.

Jika ispublic adalah true, kelas ekspresi reguler yang dikompilasi diberikan aksesibilitas publik. Artinya, itu dapat diinstansiasi dari kode yang dijalankan di perakitan apa pun. Jika ispublic adalah false, kelas ekspresi reguler yang dikompilasi diberikan internal (dalam C#) atau Friend (dalam Visual Basic) aksesibilitas. Artinya, itu hanya dapat diinstansiasi dari kode yang dijalankan dalam rakitan yang sama dengan kelas ekspresi reguler.

Parameter matchTimeout menentukan interval waktu habis default untuk ekspresi reguler yang dikompilasi. Nilai ini menunjukkan perkiraan waktu objek ekspresi reguler yang dikompilasi akan menjalankan satu operasi pencocokan sebelum waktu operasi habis dan mesin ekspresi reguler memberikan RegexMatchTimeoutException pengecualian selama pemeriksaan waktu berikutnya. Untuk informasi tambahan tentang nilai waktu habis, lihat MatchTimeout properti .

Penting

Kami menyarankan agar Anda selalu menetapkan nilai batas waktu default untuk ekspresi reguler yang dikompilasi. Konsumen pustaka ekspresi reguler Anda dapat mengambil alih nilai waktu habis tersebut dengan meneruskan TimeSpan nilai yang mewakili interval waktu habis baru ke kelebihan beban konstruktor ini.

Lihat juga

Berlaku untuk