RegexCompilationInfo Konstruktory

Definicja

Inicjuje nowe wystąpienie klasy RegexCompilationInfo.

Przeciążenia

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

Inicjuje RegexCompilationInfo nowe wystąpienie klasy zawierające informacje o wyrażeniu regularnym, które ma zostać uwzględnione w zestawie.

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

Inicjuje RegexCompilationInfo nowe wystąpienie klasy zawierające informacje o wyrażeniu regularnym z określoną wartością limitu czasu, która ma zostać uwzględniona w zestawie.

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

Source:
RegexCompilationInfo.cs
Source:
RegexCompilationInfo.cs
Source:
RegexCompilationInfo.cs

Inicjuje RegexCompilationInfo nowe wystąpienie klasy zawierające informacje o wyrażeniu regularnym, które ma zostać uwzględnione w zestawie.

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)

Parametry

pattern
String

Wyrażenie regularne do skompilowania.

options
RegexOptions

Opcje wyrażenia regularnego do użycia podczas kompilowania wyrażenia regularnego.

name
String

Nazwa typu reprezentującego skompilowane wyrażenie regularne.

fullnamespace
String

Przestrzeń nazw, do której należy nowy typ.

ispublic
Boolean

true aby skompilowane wyrażenie regularne było publicznie widoczne; w przeciwnym razie , false.

Wyjątki

pattern to null.

-lub-

name to null.

-lub-

fullnamespace to null.

Przykłady

Poniższy przykład tworzy i używa skompilowanego wyrażenia regularnego w dwóch krokach.

W pierwszym kroku skompiluj i wykonaj poniższy przykład kodu. Konstruktor RegexCompilationInfo w przykładzie kodu definiuje skompilowane wyrażenie regularne. Wynikiem wykonania kodu jest zestaw o nazwie FishRegex.dll zawierający skompilowany typ wyrażenia regularnego o nazwie 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

W drugim kroku skompiluj poniższy przykładowy kod przy użyciu odwołania do FishRegex.dll, a następnie uruchom wynikowy plik wykonywalny. Plik wykonywalny pasuje do ciągu docelowego przy użyciu FishRegex typu i wyświetla dopasowanie, grupę, grupę przechwytywania i pozycję indeksu dopasowań w ciągu docelowym.

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

Uwagi

Każdy parametr konstruktora RegexCompilationInfo(String, RegexOptions, String, String, Boolean) bezpośrednio odpowiada właściwości RegexCompilationInfo klasy . Ponieważ wszystkie właściwości są odczytywane/zapisywane, ich wartości można również przypisać bezpośrednio.

Metoda CompileToAssembly generuje zestaw zawierający skompilowane wyrażenia regularne. Dlatego nie należy określać Compiled jako jednej z wartości .options

Jeśli ispublic parametr ma truewartość , skompilowana klasa wyrażeń regularnych ma dostęp publiczny. Oznacza to, że można utworzyć wystąpienie z kodu wykonywanego w dowolnym zestawie. Jeśli ispublic parametr ma falsewartość , skompilowana klasa wyrażeń regularnych ma ułatwienia internal dostępu (w języku C#) lub Friend (w języku Visual Basic). Oznacza to, że można utworzyć wystąpienie tylko z kodu, który jest wykonywany w tym samym zestawie co klasa wyrażeń regularnych.

Uwagi dotyczące wywoływania

Ten konstruktor tworzy skompilowane wyrażenie regularne, które używa domyślnej wartości limitu czasu domeny aplikacji, w której jest tworzona. Jeśli wartość limitu czasu jest zdefiniowana dla domeny aplikacji, skompilowane wyrażenie regularne używa wartości InfiniteMatchTimeout, która uniemożliwia przekroczenie limitu czasu operacji dopasowania wzorca. Zalecanym konstruktorem do tworzenia skompilowanego wyrażenia regularnego jest RegexCompilationInfo(String, RegexOptions, String, String, Boolean, TimeSpan), który umożliwia ustawienie interwału limitu czasu.

Dotyczy

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

Source:
RegexCompilationInfo.cs
Source:
RegexCompilationInfo.cs
Source:
RegexCompilationInfo.cs

Inicjuje RegexCompilationInfo nowe wystąpienie klasy zawierające informacje o wyrażeniu regularnym z określoną wartością limitu czasu, która ma zostać uwzględniona w zestawie.

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)

Parametry

pattern
String

Wyrażenie regularne do skompilowania.

options
RegexOptions

Opcje wyrażenia regularnego do użycia podczas kompilowania wyrażenia regularnego.

name
String

Nazwa typu reprezentującego skompilowane wyrażenie regularne.

fullnamespace
String

Przestrzeń nazw, do której należy nowy typ.

ispublic
Boolean

true aby skompilowane wyrażenie regularne było publicznie widoczne; w przeciwnym razie , false.

matchTimeout
TimeSpan

Domyślny interwał limitu czasu dla wyrażenia regularnego.

Wyjątki

pattern to null.

-lub-

name to null.

-lub-

fullnamespace to null.

matchTimeout jest ujemna, zero lub większa niż około 24 dni.

Przykłady

W poniższym przykładzie zdefiniowano jedno skompilowane wyrażenie regularne o nazwie DuplicateChars , które identyfikuje co najmniej dwa wystąpienia tego samego znaku w ciągu wejściowym. Skompilowane wyrażenie regularne ma domyślny limit czasu 2 sekund. Podczas wykonywania przykładu tworzona jest biblioteka klas o nazwie RegexLib.dll zawierająca skompilowane wyrażenie regularne.

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

Wzorzec (\w)\1+ wyrażenia regularnego jest zdefiniowany, jak pokazano w poniższej tabeli.

Wzorce Opis
(\w) Dopasuj dowolny znak słowa i przypisz go do pierwszej grupy przechwytywania.
\1+ Dopasuj co najmniej jedno wystąpienie wartości pierwszej przechwyconej grupy.

W poniższym przykładzie użyto wyrażenia regularnego DuplicatedChars do identyfikowania zduplikowanych znaków w tablicy ciągów. Po wywołaniu konstruktora DuplicatedChars zmienia interwał limitu czasu na 0,5 sekundy.

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

Uwagi

Każdy parametr konstruktora RegexCompilationInfo(String, RegexOptions, String, String, Boolean) bezpośrednio odpowiada właściwości RegexCompilationInfo klasy . Ponieważ wszystkie właściwości są odczytywane/zapisywane, ich wartości można również przypisać bezpośrednio.

Metoda CompileToAssembly generuje zestaw zawierający skompilowane wyrażenia regularne. Dlatego nie należy określać Compiled jako jednej z wartości .options

Jeśli ispublic parametr ma truewartość , skompilowana klasa wyrażeń regularnych ma dostęp publiczny. Oznacza to, że można utworzyć wystąpienie z kodu wykonywanego w dowolnym zestawie. Jeśli ispublic parametr ma falsewartość , skompilowana klasa wyrażeń regularnych ma ułatwienia internal dostępu (w języku C#) lub Friend (w języku Visual Basic). Oznacza to, że można utworzyć wystąpienie tylko z kodu, który jest wykonywany w tym samym zestawie co klasa wyrażeń regularnych.

Parametr matchTimeout definiuje domyślny interwał limitu czasu dla skompilowanego wyrażenia regularnego. Ta wartość reprezentuje przybliżoną ilość czasu, przez jaką skompilowany obiekt wyrażenia regularnego wykona pojedynczą operację dopasowania przed przekroczeniem limitu czasu operacji, a aparat wyrażeń regularnych RegexMatchTimeoutException zgłasza wyjątek podczas następnego sprawdzania chronometrażu. Aby uzyskać dodatkowe informacje na temat wartości limitu czasu, zobacz MatchTimeout właściwość .

Ważne

Zalecamy, aby zawsze ustawiać domyślną wartość limitu czasu dla skompilowanego wyrażenia regularnego. Użytkownicy biblioteki wyrażeń regularnych mogą zastąpić tę wartość limitu czasu, przekazując wartość reprezentującą TimeSpan nowy interwał limitu czasu dla tego przeciążenia konstruktora.

Zobacz też

Dotyczy