Compartir a través de


Clases de expresiones regulares

Actualización: noviembre 2007

En las siguientes secciones se describen las clases de expresiones regulares de .NET Framework.

Regex

La clase Regex representa una expresión regular inmutable (de sólo lectura). Contiene también métodos estáticos que permiten utilizar otras clases de expresiones regulares sin crear explícitamente instancias de objetos de las otras clases.

En el siguiente ejemplo de código se crea una instancia de la clase Regex y se define una expresión regular simple cuando se inicializa el objeto. Observe que se utiliza una barra diagonal inversa adicional como carácter de escape para indicar que la barra diagonal inversa de la clase de caracteres de coincidencia \\s debe interpretarse como un literal de cadena.

' 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 clase Match representa el resultado de una operación de búsqueda de coincidencias de expresiones regulares. En el ejemplo siguiente se utiliza el método Match de la clase Regex para devolver un objeto de tipo Match con el fin de buscar la primera coincidencia de la cadena de entrada. En el ejemplo se utiliza la propiedad Match.Success de la clase Match para indicar si se ha encontrado alguna coincidencia.

' Create 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. 
    Console.WriteLine("Found match at position " & m.Index.ToString())
End If
  ' The example displays the following output:
  '       Found match at position 3      
 // 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. 
     Console.WriteLine("Found match at position " + m.Index);
 }
// The example displays the following output:
//       Found match at position 3      

MatchCollection

La clase MatchCollection representa una secuencia de coincidencias correctas no solapadas. La colección es inmutable (de sólo lectura) y no tiene constructor público. El método Regex.Matches devuelve instancias de MatchCollection.

En el siguiente ejemplo se utiliza el método Matches de la clase Regex para rellenar MatchCollection con todas las coincidencias encontradas en la cadena de entrada. En este ejemplo se copia la colección en una matriz de cadenas que almacena las coincidencias y en una matriz de enteros que indica la posición de cada una de ellas.

 Dim mc As MatchCollection
 Dim results As New List(Of String)
 Dim matchposition As New List(Of 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.
 For i As Integer = 0 To mc.Count - 1
     ' Add the match string to the string array.
     results.Add(mc(i).Value)
     ' Record the character position where the match was found.
     matchposition.Add(mc(i).Index)
 Next i
 ' List the results.
 For ctr As Integer = 0 To Results.Count - 1
   Console.WriteLine("'{0}' found at position {1}.", _
                     results(ctr), matchposition(ctr))  
 Next
' The example displays the following output:
'       'abc' found at position 3.
'       'abc' found at position 7.
MatchCollection mc;
List<string> results = new List<string>();
List<int> matchposition = new List<int>();

// 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.Add(mc[i].Value);
   // Record the character position where the match was found.
   matchposition.Add(mc[i].Index);   
}
// List the results.
for(int ctr = 0; ctr <= results.Count - 1; ctr++)
   Console.WriteLine("'{0}' found at position {1}.", results[ctr], matchposition[ctr]);   

// The example displays the following output:
//       'abc' found at position 3.
//       'abc' found at position 7.

GroupCollection

La clase GroupCollection representa una colección de grupos capturados y devuelve el conjunto de grupos capturados en una única coincidencia. La colección es inmutable (de sólo lectura) y no tiene constructor público. Las instancias de GroupCollection se devuelven en la colección que devuelve la propiedad Match.Groups.

En el siguiente ejemplo se busca e imprime el número de grupos capturados por una expresión regular. Para ver la forma en que se extraen las capturas individuales en cada miembro de una colección de grupos, vea el ejemplo Capture Collection de la siguiente sección.

' 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)
' The example displays the following output:
'       Number of groups found = 3
// 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);
// The example displays the following output:
//       Number of groups found = 3

CaptureCollection

La clase CaptureCollection representa una secuencia de subcadenas capturadas y devuelve el conjunto de capturas realizadas por un único grupo de capturas. Un grupo de capturas puede capturar más de una cadena en una única coincidencia gracias a los cuantificadores. La propiedad Captures, que es un objeto de la clase CaptureCollection, es un miembro de las clases Match y Group que se proporciona para facilitar el acceso al conjunto de subcadenas capturadas.

Si utiliza, por ejemplo, la expresión regular ((a(b))c)+ (en la que el cuantificador + indica una o varias coincidencias) para capturar coincidencias de la cadena abcabcabc, la CaptureCollection de cada Group coincidente de subcadenas contendrá tres miembros.

En el siguiente ejemplo se utiliza la expresión regular (Abc)+ para buscar una o más coincidencias de la cadena "XYZAbcAbcAbcXYZAbcAb". El ejemplo ilustra la forma en que se utiliza la propiedad Captures para que devuelva varios grupos de subcadenas capturadas.

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

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

    ' Display the number of captures in this group.
    Console.WriteLine("Captures count = " & counter.ToString())

    ' Loop through each capture in the group.            
    For ii = 0 To counter - 1
        ' Display the capture and its position.
        Console.WriteLine(cc(ii).ToString() _
            & "   Starts at character " & cc(ii).Index.ToString())
    Next ii
Next i
' The example displays the following 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  
   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;

   // Display 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;

      // Display the number of captures in this group.
      Console.WriteLine("Captures count = " + counter.ToString());

      // Loop through each capture in the group.
      for (int ii = 0; ii < counter; ii++) 
      {
         // Display the capture and its position.
         Console.WriteLine(cc[ii] + "   Starts at character " + 
              cc[ii].Index);
      }
   }
}
// The example displays the following 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  

Grupo

La clase Group representa el resultado de un único grupo de capturas. Dado que Group puede capturar ninguna, una o varias cadenas en una sola coincidencia (mediante los cuantificadores), contiene una colección de objetos Capture. Como Group se hereda de Capture, se puede tener acceso directo a la última subcadena capturada directamente (la propia instancia de Group es equivalente al último elemento de la colección devuelto por la propiedad Captures).

Las instancias de Group son devueltas al indizar el objeto GroupCollection devuelto por la propiedad Groups. El indizador puede ser un número de grupo o el nombre de un grupo captura si se utiliza el "(?<groupname>)" que agrupa la construcción. Por ejemplo, en código de C# puede utilizar Match.Groups[groupnum] o Match.Groups["groupname"]o en código de Visual Basic puede utilizar Match.Groups(groupnum) o Match.Groups("groupname").

En el siguiente ejemplo de código se utilizan construcciones de agrupamiento anidadas para capturar subcadenas en grupos.

 Dim matchposition As New List(Of Integer)
 Dim results As New List(Of 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 = "")    
    ' Add groups to string array.
    results.Add(m.Groups(i).Value)     
    ' Record character position. 
    matchposition.Add(m.Groups(i).Index) 
     i += 1
 End While

 ' Display the capture groups.
 For ctr As Integer = 0 to results.Count - 1
    Console.WriteLine("{0} at position {1}", _ 
                      results(ctr), matchposition(ctr))
 Next                     
' The example displays the following output:
'       abc at position 3
'       ab at position 3
'       b at position 4
List<int> matchposition = new List<int>();
List<string> results = new List<string>();
// 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++) 
{
   // Add groups to string array.
   results.Add(m.Groups[i].Value); 
   // Record character position.
   matchposition.Add(m.Groups[i].Index); 
}

// Display the capture groups.
for (int ctr = 0; ctr < results.Count; ctr++)
   Console.WriteLine("{0} at position {1}", 
                     results[ctr], matchposition[ctr]);
// The example displays the following output:
//       abc at position 3
//       ab at position 3
//       b at position 4

En el siguiente ejemplo de código se utilizan construcciones de agrupamiento con nombre para capturar subcadenas de una cadena que contiene datos en un formato "NOMBREDATOS:VALOR" que la expresión regular divide por el signo de dos puntos (:).

Dim r As New Regex("^(?<name>\w+):(?<value>\w+)")
Dim m As Match = r.Match("Section1:119900")
Console.WriteLine(m.Groups("name").Value)
Console.WriteLine(m.Groups("value").Value)
' The example displays the following output:
'       Section1
'       119900
Regex r = new Regex("^(?<name>\\w+):(?<value>\\w+)");
Match m = r.Match("Section1:119900");
Console.WriteLine(m.Groups["name"].Value);
Console.WriteLine(m.Groups["value"].Value);
// The example displays the following output:
//       Section1
//       119900

Capture

La clase Capture contiene el resultado de una única captura de subexpresiones.

En el siguiente ejemplo se recorre mediante un bucle una colección Group, se extrae la colección Capture de cada miembro de Group y se asignan las variables posn y length a la posición de carácter de la cadena original donde se encontró cada cadena Capture y a la longitud de cada cadena Capture, respectivamente.

 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
 Do While m.Groups(i).Value <> ""
    Console.WriteLine(m.Groups(i).Value)
    ' Grab the Collection for Group(i).
    cc = m.Groups(i).Captures
    For j = 0 To cc.Count - 1

       Console.WriteLine("   Capture at position {0} for {1} characters.", _ 
                         cc(j).Length, cc(j).Index)
       ' Position of Capture object.
       posn = cc(j).Index
       ' Length of Capture object.
       length = cc(j).Length
    Next j
    i += 1
 Loop
' The example displays the following output:
'       abcabc
'          Capture at position 6 for 2 characters.
'       abc
'          Capture at position 3 for 2 characters.
'          Capture at position 3 for 5 characters.
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++) 
{
   Console.WriteLine(m.Groups[i].Value);
   // Capture the Collection for Group(i).
   cc = m.Groups[i].Captures; 
   for (int j = 0; j < cc.Count; j++) 
   {
      Console.WriteLine("   Capture at position {0} for {1} characters.", 
                        cc[j].Length, cc[j].Index);
      // Position of Capture object.
      posn = cc[j].Index; 
      // Length of Capture object.
      length = cc[j].Length; 
   }
}
// The example displays the following output:
//       abcabc
//          Capture at position 6 for 2 characters.
//       abc
//          Capture at position 3 for 2 characters.
//          Capture at position 3 for 5 characters.

Vea también

Referencia

System.Text.RegularExpressions

Otros recursos

Expresiones regulares de .NET Framework