Condividi tramite


Classi di espressioni regolari

Nelle sezioni riportate di seguito vengono descritte le classi delle espressioni regolari di .NET Framework.

Regex

La classe Regex rappresenta un'espressione regolare immutabile, ovvero in sola lettura. Contiene inoltre i metodi statici che consentono di utilizzare altre classi di espressioni regolari senza creare in modo esplicito istanze delle altre classi.

Nell'esempio di codice che segue viene creata un'istanza della classe Regex e viene definita un'espressione regolare semplice al momento dell'inizializzazione dell'oggetto. L'uso di una barra rovesciata aggiuntiva come carattere di escape indica che la barra rovesciata presente nella classe del carattere di corrispondenza \s è un carattere effettivo.

    ' Declare object variable of type Regex.
    Dim r As Regex 
    ' Create a Regex object and define its regular expression.
    r = New Regex("\s2000")
    // Declare object variable of type Regex.
    Regex r; 
    // Create a Regex object and define its regular expression.
    r = new Regex("\\s2000"); 

Match

La classe Match rappresenta i risultati di un'analisi basata su un'espressione regolare. Nell'esempio che segue viene utilizzato il metodo Match della classe Regex per restituire un oggetto di tipo Match al fine di trovare la prima corrispondenza nella stringa di input. Nell'esempio viene utilizzata la proprietà Match.Success della classe Match per indicare se è stata trovata una corrispondenza.

    ' cCreate a new Regex object.
    Dim r As New Regex("abc") 
    ' Find a single match in the input string.
    Dim m As Match = r.Match("123abc456") 
    If m.Success Then
        ' Print out the character position where a match was found. 
        ' (Character position 3 in this case.)
        Console.WriteLine("Found match at position " & m.Index.ToString())
    End If
    // Create a new Regex object.
    Regex r = new Regex("abc"); 
    // Find a single match in the string.
    Match m = r.Match("123abc456"); 
    if (m.Success) 
    {
        // Print out the character position where a match was found. 
        // (Character position 3 in this case.)
        Console.WriteLine("Found match at position " + m.Index);
    }

MatchCollection

La classe MatchCollection rappresenta una sequenza di corrispondenze individuate e non sovrapposte. L'insieme non è modificabile (sola lettura) e non dispone di costruttori pubblici. Le istanze di MatchCollection vengono restituite dal metodo Regex.Matches.

Nell'esempio che segue viene utilizzato il metodo Matches della classe Regex per inserire in un oggetto MatchCollection tutte le corrispondenze trovate nella stringa di input. Nell'esempio l'insieme viene copiato in una matrice di stringhe che contiene ogni corrispondenza e in una matrice integer che indica la posizione di ogni corrispondenza.

    Dim mc As MatchCollection
    Dim results(20) As String
    Dim matchposition(20) As Integer

    ' Create a new Regex object and define the regular expression.
    Dim r As New Regex("abc")
    ' Use the Matches method to find all matches in the input string.
    mc = r.Matches("123abc4abcd")
    ' Loop through the match collection to retrieve all 
    ' matches and positions.
    Dim i As Integer
    For i = 0 To mc.Count - 1
        ' Add the match string to the string array.
        results(i) = mc(i).Value
        ' Record the character position where the match was found.
        matchposition(i) = mc(i).Index
    Next i
    MatchCollection mc;
    String[] results = new String[20];
    int[] matchposition = new int[20];
    
    // Create a new Regex object and define the regular expression.
    Regex r = new Regex("abc"); 
    // Use the Matches method to find all matches in the input string.
    mc = r.Matches("123abc4abcd");
    // Loop through the match collection to retrieve all 
    // matches and positions.
    for (int i = 0; i < mc.Count; i++) 
    {
        // Add the match string to the string array.   
        results[i] = mc[i].Value;
        // Record the character position where the match was found.
        matchposition[i] = mc[i].Index;   
    }

GroupCollection

La classe GroupCollection rappresenta un insieme di gruppi catturati e lo restituisce in una singola corrispondenza. L'insieme non è modificabile (sola lettura) e non dispone di costruttori pubblici. Le istanze di GroupCollection vengono restituite nell'insieme restituito dalla proprietà Match.Groups.

L'applicazione di console che segue trova e stampa il numero di gruppi catturati da un'espressione regolare. Per un esempio di estrazione delle singole acquisizioni in ogni membro di un insieme di gruppi, vedere l'esempio CaptureCollection nella sezione che segue.

    Imports System
    Imports System.Text.RegularExpressions

    Public Class RegexTest
        Public Shared Sub RunTest()
            ' Define groups "abc", "ab", and "b".
            Dim r As New Regex("(a(b))c") 
            Dim m As Match = r.Match("abdabc")
            Console.WriteLine("Number of groups found = " _
            & m.Groups.Count.ToString())
        End Sub    
    
        Public Shared Sub Main()
            RunTest()
        End Sub
    End Class
    using System;
    using System.Text.RegularExpressions;

    public class RegexTest 
    {
        public static void RunTest() 
        {
            // Define groups "abc", "ab", and "b".
            Regex r = new Regex("(a(b))c"); 
            Match m = r.Match("abdabc");
            Console.WriteLine("Number of groups found = " + m.Groups.Count);
        }
        public static void Main() 
        {
            RunTest();
        }
    }

Questo esempio produce l'output che segue.

    Number of groups found = 3
    Number of groups found = 3

CaptureCollection

La classe CaptureCollection rappresenta una sequenza di sottostringhe catturate e restituisce l'insieme degli elementi catturati da un singolo gruppo di cattura. Un gruppo di cattura può catturare più stringhe in una singola corrispondenza grazie ai quantificatori. La proprietà Captures, un oggetto della classe CaptureCollection, viene fornita come membro delle classi Match e Group per semplificare l'accesso all'insieme di sottostringhe catturate.

Se ad esempio si utilizza l'espressione regolare ((a(b))c)+, dove il quantificatore + specifica una o più corrispondenze, per catturare corrispondenze dalla stringa "abcabcabc", il CaptureCollection di ciascun Group corrispondente di sottostringhe conterrà tre membri.

Nell'esempio di applicazione di console che segue viene utilizzata l'espressione regolare (Abc)+ per trovare una o più corrispondenze nella stringa "XYZAbcAbcAbcXYZAbcAb". Nell'esempio viene illustrato l'utilizzo della proprietà Captures per restituire più gruppi di sottostringhe catturate.

    Imports System
    Imports System.Text.RegularExpressions

    Public Class RegexTest
        Public Shared Sub RunTest()
            Dim counter As Integer
            Dim m As Match
            Dim cc As CaptureCollection
            Dim gc As GroupCollection
            ' Look for groupings of "Abc".
            Dim r As New Regex("(Abc)+") 
            ' Define the string to search.
            m = r.Match("XYZAbcAbcAbcXYZAbcAb")
            gc = m.Groups
            
            ' Print the number of groups.
            Console.WriteLine("Captured groups = " & gc.Count.ToString())
            
            ' Loop through each group.
            Dim i, ii As Integer
            For i = 0 To gc.Count - 1
                cc = gc(i).Captures
                counter = cc.Count
                
                ' Print number of captures in this group.
                Console.WriteLine("Captures count = " & counter.ToString())
                
                ' Loop through each capture in group.            
                For ii = 0 To counter - 1
                    ' Print capture and position.
                    Console.WriteLine(cc(ii).ToString() _
                        & "   Starts at character " & cc(ii).Index.ToString())
                Next ii
            Next i
        End Sub
    
        Public Shared Sub Main()
            RunTest()
         End Sub
    End Class
    using System;
    using System.Text.RegularExpressions;

    public class RegexTest 
        {
        public static void RunTest() 
        {
            int counter;
            Match m;
            CaptureCollection cc;
            GroupCollection gc;

            // Look for groupings of "Abc".
            Regex r = new Regex("(Abc)+"); 
            // Define the string to search.
            m = r.Match("XYZAbcAbcAbcXYZAbcAb"); 
            gc = m.Groups;

            // Print the number of groups.
            Console.WriteLine("Captured groups = " + gc.Count.ToString());

            // Loop through each group.
            for (int i=0; i < gc.Count; i++) 
            {
                cc = gc[i].Captures;
                counter = cc.Count;
                
                // Print number of captures in this group.
                Console.WriteLine("Captures count = " + counter.ToString());
                
                // Loop through each capture in group.
                for (int ii = 0; ii < counter; ii++) 
                {
                    // Print capture and position.
                    Console.WriteLine(cc[ii] + "   Starts at character " + 
                        cc[ii].Index);
                }
            }
        }

        public static void Main() {
            RunTest();
        }
    }

L'esempio restituisce il seguente output.

    Captured groups = 2
    Captures count = 1
    AbcAbcAbc   Starts at character 3
    Captures count = 3
    Abc   Starts at character 3
    Abc   Starts at character 6
    Abc   Starts at character 9
    Captured groups = 2
    Captures count = 1
    AbcAbcAbc   Starts at character 3
    Captures count = 3
    Abc   Starts at character 3
    Abc   Starts at character 6
    Abc   Starts at character 9

Group

La classe Group rappresenta i risultati di un singolo gruppo di cattura. Grazie ai quantificatori, in una singola corrispondenza Group può acquisire una o più stringhe o non acquisirne alcuna. Pertanto, contiene un insieme di oggetti Capture. Poiché Group eredita da Capture, è possibile accedere direttamente all'ultima sottostringa acquisita. La stessa istanza di Group è equivalente all'ultima voce dell'insieme restituito dalla proprietà Captures.

Vengono restituite istanze della classe Group indicizzando l'oggetto GroupCollection restituito dalla proprietà Groups. L'indicizzatore può essere un numero di gruppo o il nome di un gruppo di acquisizione se viene utilizzato il costrutto di raggruppamento "(?<nomegruppo>)". Nel codice C# ad esempio è possibile utilizzare Match.Groups[numgruppo] o Match.Groups["nomegruppo"] oppure nel codice Visual Basic è possibile utilizzare Match.Groups(numgruppo) o Match.Groups("nomegruppo").

Nell'esempio di codice che segue vengono utilizzati costrutti di raggruppamento nidificati per catturare sottostringhe in gruppi.

    Dim matchposition(20) As Integer
    Dim results(20) As String
    ' Define substrings abc, ab, b.
    Dim r As New Regex("(a(b))c") 
    Dim m As Match = r.Match("abdabc")
    Dim i As Integer = 0
    While Not (m.Groups(i).Value = "")    
       ' Copy groups to string array.
       results(i) = m.Groups(i).Value     
       ' Record character position. 
       matchposition(i) = m.Groups(i).Index 
        i = i + 1
    End While
    int[] matchposition = new int[20];
    String[] results = new String[20];
    // Define substrings abc, ab, b.
    Regex r = new Regex("(a(b))c"); 
    Match m = r.Match("abdabc");
    for (int i = 0; m.Groups[i].Value != ""; i++) 
    {
        // Copy groups to string array.
        results[i]=m.Groups[i].Value; 
        // Record character position.
        matchposition[i] = m.Groups[i].Index; 
    }

L'esempio restituisce il seguente output.

    results(0) = "abc"   matchposition(0) = 3
    results(1) = "ab"    matchposition(1) = 3
    results(2) = "b"     matchposition(2) = 4
    results[0] = "abc"   matchposition[0] = 3
    results[1] = "ab"    matchposition[1] = 3
    results[2] = "b"     matchposition[2] = 4

Nell'esempio di codice che segue vengono utilizzati i costrutti di raggruppamento denominati per acquisire le sottostringhe da una stringa contenente dati in formato "DATANAME:VALUE" che viene suddiviso in corrispondenza dei due punti (:) dall'espressione regolare.

    Dim r As New Regex("^(?<name>\w+):(?<value>\w+)")
    Dim m As Match = r.Match("Section1:119900")
    Regex r = new Regex("^(?<name>\\w+):(?<value>\\w+)");
    Match m = r.Match("Section1:119900");

L'espressione regolare restituisce l'output che segue.

    m.Groups("name").Value = "Section1"
    m.Groups("value").Value = "119900"
    m.Groups["name"].Value = "Section1"
    m.Groups["value"].Value = "119900"

Capture

La classe Capture contiene i risultati di una singola acquisizione di sottoespressioni.

Nell'esempio riportato di seguito si scorre un insieme Group, viene estratto l'insieme Capture da ciascun membro di Group e vengono impostate le variabili posn e length, la prima sulla posizione in cui, nella stringa originale, si trova il primo carattere di ciascuna stringa trovata e la seconda sulla lunghezza di ciascuna stringa.

    Dim r As Regex
    Dim m As Match
    Dim cc As CaptureCollection
    Dim posn, length As Integer

    r = New Regex("(abc)+")
    m = r.Match("bcabcabc")
    Dim i, j As Integer
    i = 0
    While m.Groups(i).Value <> ""
        ' Grab the Collection for Group(i).
        cc = m.Groups(i).Captures
        For j = 0 To cc.Count - 1
            ' Position of Capture object.
            posn = cc(j).Index
            ' Length of Capture object.
            length = cc(j).Length
        Next j
        i += 1
    End While
    Regex r;
    Match m;
    CaptureCollection cc;
    int posn, length;

    r = new Regex("(abc)+");
    m = r.Match("bcabcabc");
    for (int i=0; m.Groups[i].Value != ""; i++) 
    {
        // Capture the Collection for Group(i).
        cc = m.Groups[i].Captures; 
        for (int j = 0; j < cc.Count; j++) 
        {
            // Position of Capture object.
            posn = cc[j].Index; 
            // Length of Capture object.
            length = cc[j].Length; 
        }
    }

Vedere anche

Riferimenti

System.Text.RegularExpressions

Altre risorse

Espressioni regolari di .NET Framework