Delimitadores en expresiones regularesAnchors in Regular Expressions

Los delimitadores, o aserciones atómicas de ancho cero, especifican la posición de la cadena en que se debe producir una coincidencia.Anchors, or atomic zero-width assertions, specify a position in the string where a match must occur. Cuando se usa un delimitador en una expresión de búsqueda, el motor de expresiones regulares no avanza por la cadena o ni consume caracteres, sino que solo busca una coincidencia en la posición especificada.When you use an anchor in your search expression, the regular expression engine does not advance through the string or consume characters; it looks for a match in the specified position only. Por ejemplo, ^ especifica que la coincidencia debe empezar al principio de una cadena o línea.For example, ^ specifies that the match must start at the beginning of a line or string. Por consiguiente, la expresión regular ^http: coincide con "http": solo cuando se encuentra al principio de una línea.Therefore, the regular expression ^http: matches "http:" only when it occurs at the beginning of a line. En la tabla siguiente, se enumeran los delimitadores que admiten las expresiones regulares de .NET.The following table lists the anchors supported by the regular expressions in .NET.

DelimitadorAnchor DescriptionDescription
^ La coincidencia se debe producir al principio de la cadena o de la línea.The match must occur at the beginning of the string or line. Para obtener más información, vea Principio de cadena o línea.For more information, see Start of String or Line.
$ La coincidencia se debe producir al final de la cadena o de la línea, o antes de \n al final de la cadena o de la línea.The match must occur at the end of the string or line, or before \n at the end of the string or line. Para obtener más información, vea Final de cadena o línea.For more information, see End of String or Line.
\A La coincidencia se debe producir solo al principio de la cadena (no se admiten varias líneas).The match must occur at the beginning of the string only (no multiline support). Para obtener más información, vea Principio de cadena solamente.For more information, see Start of String Only.
\Z La coincidencia se debe producir al final de la cadena o antes de \n al final de la cadena.The match must occur at the end of the string, or before \n at the end of the string. Para obtener más información, vea Final de cadena o antes de nueva línea al final.For more information, see End of String or Before Ending Newline.
\z La coincidencia se debe producir solo al final de la cadena.The match must occur at the end of the string only. Para obtener más información, vea Final de cadena solamente.For more information, see End of String Only.
\G La coincidencia se debe iniciar en la posición en que finalizó la coincidencia anterior.The match must start at the position where the previous match ended. Para obtener más información, vea Coincidencias contiguas.For more information, see Contiguous Matches.
\b La coincidencia se debe producir en un límite de palabras.The match must occur on a word boundary. Para obtener más información, vea Límite de palabras.For more information, see Word Boundary.
\B La coincidencia no se debe producir en un límite de palabras.The match must not occur on a word boundary. Para obtener más información, vea Fuera de un límite de palabras.For more information, see Non-Word Boundary.

Principio de cadena o línea: ^Start of String or Line: ^

El delimitador ^ especifica que el siguiente patrón debe comenzar en la posición del primer carácter de la cadena.The ^ anchor specifies that the following pattern must begin at the first character position of the string. Si usa ^ con la opción RegexOptions.Multiline (vea Opciones de expresiones regulares), la coincidencia se debe producir al principio de cada línea.If you use ^ with the RegexOptions.Multiline option (see Regular Expression Options), the match must occur at the beginning of each line.

En el ejemplo siguiente se usa el delimitador ^ en una expresión regular que extrae información sobre los años durante los que existieron algunos equipos de béisbol profesionales.The following example uses the ^ anchor in a regular expression that extracts information about the years during which some professional baseball teams existed. En el ejemplo se llama a dos sobrecargas del método Regex.Matches:The example calls two overloads of the Regex.Matches method:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      int startPos = 0, endPos = 70;
      string input = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957\n" +
                     "Chicago Cubs, National League, 1903-present\n" + 
                     "Detroit Tigers, American League, 1901-present\n" + 
                     "New York Giants, National League, 1885-1957\n" +  
                     "Washington Senators, American League, 1901-1960\n";   
      string pattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+";
      Match match;
      
      if (input.Substring(startPos, endPos).Contains(",")) {
         match = Regex.Match(input, pattern);
         while (match.Success) {
            Console.Write("The {0} played in the {1} in", 
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
   
            Console.WriteLine(".");
            startPos = match.Index + match.Length;
            endPos = startPos + 70 <= input.Length ? 70 : input.Length - startPos;
            if (! input.Substring(startPos, endPos).Contains(",")) break;
            match = match.NextMatch();
         }
         Console.WriteLine();
      }
         
      if (input.Substring(startPos, endPos).Contains(",")) {
         match = Regex.Match(input, pattern, RegexOptions.Multiline);
         while (match.Success) {
            Console.Write("The {0} played in the {1} in", 
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
   
            Console.WriteLine(".");
            startPos = match.Index + match.Length;
            endPos = startPos + 70 <= input.Length ? 70 : input.Length - startPos;
            if (! input.Substring(startPos, endPos).Contains(",")) break;
            match = match.NextMatch();
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    The Chicago Cubs played in the National League in 1903-present.
//    The Detroit Tigers played in the American League in 1901-present.
//    The New York Giants played in the National League in 1885-1957.
//    The Washington Senators played in the American League in 1901-1960.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim startPos As Integer = 0
      Dim endPos As Integer = 70
      Dim input As String = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + vbCrLf + _
                            "Chicago Cubs, National League, 1903-present" + vbCrLf + _
                            "Detroit Tigers, American League, 1901-present" + vbCrLf + _
                            "New York Giants, National League, 1885-1957" + vbCrLf + _
                            "Washington Senators, American League, 1901-1960" + vbCrLf  

      Dim pattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"
      Dim match As Match
      
      ' Provide minimal validation in the event the input is invalid.
      If input.Substring(startPos, endPos).Contains(",") Then
         match = Regex.Match(input, pattern)
         Do While match.Success
            Console.Write("The {0} played in the {1} in", _
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            startPos = match.Index + match.Length 
            endPos = CInt(IIf(startPos + 70 <= input.Length, 70, input.Length - startPos))
            If Not input.Substring(startPos, endPos).Contains(",") Then Exit Do
            match = match.NextMatch()            
         Loop
         Console.WriteLine()                               
      End If      

      startPos = 0
      endPos = 70
      If input.Substring(startPos, endPos).Contains(",") Then
         match = Regex.Match(input, pattern, RegexOptions.Multiline)
         Do While match.Success
            Console.Write("The {0} played in the {1} in", _
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            startPos = match.Index + match.Length 
            endPos = CInt(IIf(startPos + 70 <= input.Length, 70, input.Length - startPos))
            If Not input.Substring(startPos, endPos).Contains(",") Then Exit Do
            match = match.NextMatch()            
         Loop
         Console.WriteLine()                               
      End If      

      
'       For Each match As Match in Regex.Matches(input, pattern, RegexOptions.Multiline)
'          Console.Write("The {0} played in the {1} in", _
'                            match.Groups(1).Value, match.Groups(4).Value)
'          For Each capture As Capture In match.Groups(5).Captures
'             Console.Write(capture.Value)
'          Next
'          Console.WriteLine(".")
'       Next
   End Sub
End Module
' The example displays the following output:
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    The Chicago Cubs played in the National League in 1903-present.
'    The Detroit Tigers played in the American League in 1901-present.
'    The New York Giants played in the National League in 1885-1957.
'    The Washington Senators played in the American League in 1901-1960.

El patrón de expresión regular ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+ se define como se muestra en la tabla siguiente.The regular expression pattern ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+ is defined as shown in the following table.

ModeloPattern DescriptionDescription
^ Comienza la búsqueda de coincidencias al principio de la cadena de entrada (o al principio de la línea si se llama al método con la opción RegexOptions.Multiline).Begin the match at the beginning of the input string (or the beginning of the line if the method is called with the RegexOptions.Multiline option).
((\w+(\s?)){2,} Coincide con uno o varios caracteres que se usan para formar palabras seguidos de cero o un espacio, exactamente dos veces.Match one or more word characters followed either by zero or by one space exactly two times. Este es el primer grupo de captura.This is the first capturing group. Esta expresión también define un segundo y un tercer grupo de capturas: el segundo está compuesto por la palabra capturada y el tercero está compuesto por los espacios capturados.This expression also defines a second and third capturing group: The second consists of the captured word, and the third consists of the captured spaces.
,\s Coincide con una coma seguida de un carácter de espacio en blanco.Match a comma followed by a white-space character.
(\w+\s\w+) Coincide con uno o varios caracteres que se usan para formar palabras seguidos de un espacio, seguidos de uno o varios caracteres que se usan para formar palabras.Match one or more word characters followed by a space, followed by one or more word characters. Este es el cuarto grupo de captura.This is the fourth capturing group.
, Coincide con una coma.Match a comma.
\s\d{4} Coincide con un espacio seguido de cuatro dígitos decimales.Match a space followed by four decimal digits.
(-(\d{4}|present))? Coincide con cero o un guion seguido de cuatro dígitos decimales o de la cadena "present".Match zero or one occurrence of a hyphen followed by four decimal digits or the string "present". Este es el sexto grupo de captura.This is the sixth capturing group. También incluye un séptimo grupo de captura.It also includes a seventh capturing group.
,? Coincide con una coma o ninguna.Match zero or one occurrence of a comma.
(\s\d{4}(-(\d{4}|present))?,?)+ Coincide con una o más apariciones de lo siguiente: un espacio, cuatro dígitos decimales, cero o un guion seguido de cuatro dígitos decimales o de la cadena "present", y una coma o ninguna.Match one or more occurrences of the following: a space, four decimal digits, zero or one occurrence of a hyphen followed by four decimal digits or the string "present", and zero or one comma. Este es el quinto grupo de captura.This is the fifth capturing group.

Volver al principioBack to top

Final de cadena o línea: $End of String or Line: $

El delimitador $ especifica que el patrón que le precede debe aparecer al final de la cadena de entrada o antes de \n al final de la cadena de entrada.The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string.

Si usa $ con la opción RegexOptions.Multiline, la coincidencia también se puede producir al final de una línea.If you use $ with the RegexOptions.Multiline option, the match can also occur at the end of a line. Observe que $ coincide con \n , pero no coincide con \r\n (la combinación de caracteres de retorno de carro y nueva línea, o CR/LF).Note that $ matches \n but does not match \r\n (the combination of carriage return and newline characters, or CR/LF). Para buscar la combinación de caracteres CR/LF, incluya \r?$ en el patrón de expresión regular.To match the CR/LF character combination, include \r?$ in the regular expression pattern.

En el ejemplo siguiente se agrega el delimitador $ al patrón de expresión regular usado en el ejemplo de la sección Principio de cadena o línea .The following example adds the $ anchor to the regular expression pattern used in the example in the Start of String or Line section. Cuando se usa con la cadena de entrada original, que incluye cinco líneas de texto, el método Regex.Matches(String, String) no puede encontrar una coincidencia, porque el final de la primera línea no coincide con el patrón $.When used with the original input string, which includes five lines of text, the Regex.Matches(String, String) method is unable to find a match, because the end of the first line does not match the $ pattern. Cuando la cadena de entrada original se divide en una matriz de cadenas, el método Regex.Matches(String, String) consigue encontrar coincidencias en cada una de las cinco líneas.When the original input string is split into a string array, the Regex.Matches(String, String) method succeeds in matching each of the five lines. Cuando se llama al método Regex.Matches(String, String, RegexOptions) con el parámetro options establecido en RegexOptions.Multiline, no se encuentra ninguna coincidencia porque el patrón de la expresión regular no tiene en cuenta el elemento de retorno de carro (\u+000D).When the Regex.Matches(String, String, RegexOptions) method is called with the options parameter set to RegexOptions.Multiline, no matches are found because the regular expression pattern does not account for the carriage return element (\u+000D). Sin embargo, cuando el patrón de la expresión regular se modifica al remplazar $ por \r?$, si se llama al método Regex.Matches(String, String, RegexOptions) con el parámetro options establecido en RegexOptions.Multiline, ahora encuentra cinco coincidencias.However, when the regular expression pattern is modified by replacing $ with \r?$, calling the Regex.Matches(String, String, RegexOptions) method with the options parameter set to RegexOptions.Multiline again finds five matches.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      int startPos = 0, endPos = 70;
      string cr = Environment.NewLine;
      string input = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + cr +
                     "Chicago Cubs, National League, 1903-present" + cr + 
                     "Detroit Tigers, American League, 1901-present" + cr + 
                     "New York Giants, National League, 1885-1957" + cr +  
                     "Washington Senators, American League, 1901-1960" + cr;   
      Match match;

      string basePattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+";
      string pattern = basePattern + "$";
      Console.WriteLine("Attempting to match the entire input string:");
      if (input.Substring(startPos, endPos).Contains(",")) {
         match = Regex.Match(input, pattern);
         while (match.Success) {
            Console.Write("The {0} played in the {1} in", 
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
   
            Console.WriteLine(".");
            startPos = match.Index + match.Length;
            endPos = startPos + 70 <= input.Length ? 70 : input.Length - startPos;
            if (! input.Substring(startPos, endPos).Contains(",")) break;
            match = match.NextMatch();
         }
         Console.WriteLine();
      }

      string[] teams = input.Split(new String[] { cr }, StringSplitOptions.RemoveEmptyEntries);
      Console.WriteLine("Attempting to match each element in a string array:");
      foreach (string team in teams)
      {
         if (team.Length > 70) continue;

         match = Regex.Match(team, pattern);
         if (match.Success)
         {
            Console.Write("The {0} played in the {1} in", 
                          match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
            Console.WriteLine(".");
         }
      }
      Console.WriteLine();
      
      startPos = 0;
      endPos = 70;
      Console.WriteLine("Attempting to match each line of an input string with '$':");
      if (input.Substring(startPos, endPos).Contains(",")) {
         match = Regex.Match(input, pattern, RegexOptions.Multiline);
         while (match.Success) {
            Console.Write("The {0} played in the {1} in", 
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
   
            Console.WriteLine(".");
            startPos = match.Index + match.Length;
            endPos = startPos + 70 <= input.Length ? 70 : input.Length - startPos;
            if (! input.Substring(startPos, endPos).Contains(",")) break;
            match = match.NextMatch();
         }
         Console.WriteLine();
      }
      
      startPos = 0;
      endPos = 70;
      pattern = basePattern + "\r?$"; 
      Console.WriteLine(@"Attempting to match each line of an input string with '\r?$':");
      if (input.Substring(startPos, endPos).Contains(",")) {
         match = Regex.Match(input, pattern, RegexOptions.Multiline);
         while (match.Success) {
            Console.Write("The {0} played in the {1} in", 
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
   
            Console.WriteLine(".");
            startPos = match.Index + match.Length;
            endPos = startPos + 70 <= input.Length ? 70 : input.Length - startPos;
            if (! input.Substring(startPos, endPos).Contains(",")) break;
            match = match.NextMatch();
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    Attempting to match the entire input string:
//    
//    Attempting to match each element in a string array:
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    The Chicago Cubs played in the National League in 1903-present.
//    The Detroit Tigers played in the American League in 1901-present.
//    The New York Giants played in the National League in 1885-1957.
//    The Washington Senators played in the American League in 1901-1960.
//    
//    Attempting to match each line of an input string with '$':
//    
//    Attempting to match each line of an input string with '\r+$':
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    The Chicago Cubs played in the National League in 1903-present.
//    The Detroit Tigers played in the American League in 1901-present.
//    The New York Giants played in the National League in 1885-1957.
//    The Washington Senators played in the American League in 1901-1960.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim startPos As Integer = 0
      Dim endPos As Integer = 70
      Dim input As String = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + vbCrLf + _
                            "Chicago Cubs, National League, 1903-present" + vbCrLf + _
                            "Detroit Tigers, American League, 1901-present" + vbCrLf + _
                            "New York Giants, National League, 1885-1957" + vbCrLf + _
                            "Washington Senators, American League, 1901-1960" + vbCrLf  

      Dim basePattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"
      Dim match As Match

      Dim pattern As String = basePattern + "$"
      Console.WriteLine("Attempting to match the entire input string:")
      ' Provide minimal validation in the event the input is invalid.
      If input.Substring(startPos, endPos).Contains(",") Then
         match = Regex.Match(input, pattern)
         Do While match.Success
            Console.Write("The {0} played in the {1} in", _
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            startPos = match.Index + match.Length 
            endPos = CInt(IIf(startPos + 70 <= input.Length, 70, input.Length - startPos))
            If Not input.Substring(startPos, endPos).Contains(",") Then Exit Do
            match = match.NextMatch()            
         Loop
         Console.WriteLine()                               
      End If      
      
      Dim teams() As String = input.Split(New String() { vbCrLf }, StringSplitOptions.RemoveEmptyEntries)
      Console.WriteLine("Attempting to match each element in a string array:")
      For Each team As String In teams
         If team.Length > 70 Then Continue For
         match = Regex.Match(team, pattern)
         If match.Success Then
            Console.Write("The {0} played in the {1} in", _
                           match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
         End If
      Next
      Console.WriteLine()
      
      startPos = 0
      endPos = 70
      Console.WriteLine("Attempting to match each line of an input string with '$':")
      ' Provide minimal validation in the event the input is invalid.
      If input.Substring(startPos, endPos).Contains(",") Then
         match = Regex.Match(input, pattern, RegexOptions.Multiline)
         Do While match.Success
            Console.Write("The {0} played in the {1} in", _
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            startPos = match.Index + match.Length 
            endPos = CInt(IIf(startPos + 70 <= input.Length, 70, input.Length - startPos))
            If Not input.Substring(startPos, endPos).Contains(",") Then Exit Do
            match = match.NextMatch()            
         Loop
         Console.WriteLine()                               
      End If      

      
      startPos = 0
      endPos = 70
      pattern = basePattern + "\r?$" 
      Console.WriteLine("Attempting to match each line of an input string with '\r?$':")
      ' Provide minimal validation in the event the input is invalid.
      If input.Substring(startPos, endPos).Contains(",") Then
         match = Regex.Match(input, pattern, RegexOptions.Multiline)
         Do While match.Success
            Console.Write("The {0} played in the {1} in", _
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            startPos = match.Index + match.Length 
            endPos = CInt(IIf(startPos + 70 <= input.Length, 70, input.Length - startPos))
            If Not input.Substring(startPos, endPos).Contains(",") Then Exit Do
            match = match.NextMatch()            
         Loop
         Console.WriteLine()                               
      End If      
   End Sub
End Module
' The example displays the following output:
'    Attempting to match the entire input string:
'    
'    Attempting to match each element in a string array:
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    The Chicago Cubs played in the National League in 1903-present.
'    The Detroit Tigers played in the American League in 1901-present.
'    The New York Giants played in the National League in 1885-1957.
'    The Washington Senators played in the American League in 1901-1960.
'    
'    Attempting to match each line of an input string with '$':
'    
'    Attempting to match each line of an input string with '\r+$':
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    The Chicago Cubs played in the National League in 1903-present.
'    The Detroit Tigers played in the American League in 1901-present.
'    The New York Giants played in the National League in 1885-1957.
'    The Washington Senators played in the American League in 1901-1960.

Volver al principioBack to top

Principio de cadena solamente: \AStart of String Only: \A

El delimitador \A especifica que debe producirse una coincidencia al principio de la cadena de entrada.The \A anchor specifies that a match must occur at the beginning of the input string. Es idéntico al delimitador ^, salvo en que \A omite la opción RegexOptions.Multiline.It is identical to the ^ anchor, except that \A ignores the RegexOptions.Multiline option. Por consiguiente, solo puede coincidir con el principio de la primera línea en una cadena de entrada de varias líneas.Therefore, it can only match the start of the first line in a multiline input string.

El ejemplo siguiente es similar a los ejemplos de los delimitadores ^ y $ .The following example is similar to the examples for the ^ and $ anchors. Usa el delimitador \A en una expresión regular que extrae información sobre los años durante los que existieron algunos equipos de béisbol profesionales.It uses the \A anchor in a regular expression that extracts information about the years during which some professional baseball teams existed. La cadena de entrada incluye cinco líneas.The input string includes five lines. La llamada al método Regex.Matches(String, String, RegexOptions) encuentra solo la primera subcadena que coincide con el patrón de la expresión regular en la cadena de entrada.The call to the Regex.Matches(String, String, RegexOptions) method finds only the first substring in the input string that matches the regular expression pattern. Como muestra el ejemplo, la opción Multiline no tiene ningún efecto.As the example shows, the Multiline option has no effect.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      int startPos = 0, endPos = 70;
      string input = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957\n" +
                     "Chicago Cubs, National League, 1903-present\n" + 
                     "Detroit Tigers, American League, 1901-present\n" + 
                     "New York Giants, National League, 1885-1957\n" +  
                     "Washington Senators, American League, 1901-1960\n";   

      string pattern = @"\A((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+";
      Match match;

      if (input.Substring(startPos, endPos).Contains(",")) {
         match = Regex.Match(input, pattern, RegexOptions.Multiline);
         while (match.Success) {
            Console.Write("The {0} played in the {1} in", 
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
               Console.Write(capture.Value);
   
            Console.WriteLine(".");
            startPos = match.Index + match.Length;
            endPos = startPos + 70 <= input.Length ? 70 : input.Length - startPos;
            if (! input.Substring(startPos, endPos).Contains(",")) break;
            match = match.NextMatch();
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim startPos As Integer = 0
      Dim endPos As Integer = 70
      Dim input As String = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + vbCrLf + _
                            "Chicago Cubs, National League, 1903-present" + vbCrLf + _
                            "Detroit Tigers, American League, 1901-present" + vbCrLf + _
                            "New York Giants, National League, 1885-1957" + vbCrLf + _
                            "Washington Senators, American League, 1901-1960" + vbCrLf  

      Dim pattern As String = "\A((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"
      Dim match As Match
      
      ' Provide minimal validation in the event the input is invalid.
      If input.Substring(startPos, endPos).Contains(",") Then
         match = Regex.Match(input, pattern, RegexOptions.Multiline)
         Do While match.Success
            Console.Write("The {0} played in the {1} in", _
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
               Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            startPos = match.Index + match.Length 
            endPos = CInt(IIf(startPos + 70 <= input.Length, 70, input.Length - startPos))
            If Not input.Substring(startPos, endPos).Contains(",") Then Exit Do
            match = match.NextMatch()            
         Loop
         Console.WriteLine()                               
      End If      
   End Sub   
End Module
' The example displays the following output:
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.

Volver al principioBack to top

Final de cadena o antes de nueva línea al final: \ZEnd of String or Before Ending Newline: \Z

El delimitador \Z especifica que se debe producir una coincidencia al final de la cadena de entrada o antes de \n al final de la cadena de entrada.The \Z anchor specifies that a match must occur at the end of the input string, or before \n at the end of the input string. Es idéntico al delimitador $, salvo en que \Z omite la opción RegexOptions.Multiline.It is identical to the $ anchor, except that \Z ignores the RegexOptions.Multiline option. Por consiguiente, en una cadena de varias líneas, solo puede coincidir con el final de la última línea o la última línea antes de \n.Therefore, in a multiline string, it can only match the end of the last line, or the last line before \n.

Observe que \Z coincide con \n , pero no coincide con \r\n (la combinación de caracteres de retorno de carro y nueva línea, o CR/LF).Note that \Z matches \n but does not match \r\n (the CR/LF character combination). Para buscar CR/LF, incluya \r?\Z en el patrón de expresión regular.To match CR/LF, include \r?\Z in the regular expression pattern.

En el ejemplo siguiente, se usa el delimitador \Z en una expresión regular que es similar al ejemplo de la sección Principio de cadena o línea , que extrae información sobre los años durante los que existieron algunos equipos del béisbol profesionales.The following example uses the \Z anchor in a regular expression that is similar to the example in the Start of String or Line section, which extracts information about the years during which some professional baseball teams existed. La subexpresión \r?\Z de la expresión regular ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z coincide con el final de una cadena, y también coincide con una cadena que termina por \n o \r\n.The subexpression \r?\Z in the regular expression ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z matches the end of a string, and also matches a string that ends with \n or \r\n. Como resultado, cada elemento de la matriz coincide con el patrón de la expresión regular.As a result, each element in the array matches the regular expression pattern.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] inputs = { "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",  
                          "Chicago Cubs, National League, 1903-present" + Environment.NewLine, 
                          "Detroit Tigers, American League, 1901-present" + Regex.Unescape(@"\n"), 
                          "New York Giants, National League, 1885-1957", 
                          "Washington Senators, American League, 1901-1960" + Environment.NewLine}; 
      string pattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z";

      foreach (string input in inputs)
      {
         if (input.Length > 70 || ! input.Contains(",")) continue;
         
         Console.WriteLine(Regex.Escape(input));
         Match match = Regex.Match(input, pattern);
         if (match.Success)
            Console.WriteLine("   Match succeeded.");
         else
            Console.WriteLine("   Match failed.");
      }   
   }
}
// The example displays the following output:
//    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
//       Match succeeded.
//    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
//       Match succeeded.
//    Detroit\ Tigers,\ American\ League,\ 1901-present\n
//       Match succeeded.
//    New\ York\ Giants,\ National\ League,\ 1885-1957
//       Match succeeded.
//    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
//       Match succeeded.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim inputs() As String = { "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",  _
                            "Chicago Cubs, National League, 1903-present" + vbCrLf, _
                            "Detroit Tigers, American League, 1901-present" + vbLf, _
                            "New York Giants, National League, 1885-1957", _
                            "Washington Senators, American League, 1901-1960" + vbCrLf }  
      Dim pattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z"

      For Each input As String In inputs
         If input.Length > 70 Or Not input.Contains(",") Then Continue For
         
         Console.WriteLine(Regex.Escape(input))
         Dim match As Match = Regex.Match(input, pattern)
         If match.Success Then
            Console.WriteLine("   Match succeeded.")
         Else
            Console.WriteLine("   Match failed.")
         End If
      Next   
   End Sub
End Module
' The example displays the following output:
'    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
'       Match succeeded.
'    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
'       Match succeeded.
'    Detroit\ Tigers,\ American\ League,\ 1901-present\n
'       Match succeeded.
'    New\ York\ Giants,\ National\ League,\ 1885-1957
'       Match succeeded.
'    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
'       Match succeeded.

Volver al principioBack to top

Final de cadena solamente: \zEnd of String Only: \z

El delimitador \z especifica que debe producirse una coincidencia al final de la cadena de entrada.The \z anchor specifies that a match must occur at the end of the input string. Al igual que el elemento del lenguaje $, \z omite la opción RegexOptions.Multiline.Like the $ language element, \z ignores the RegexOptions.Multiline option. A diferencia del elemento del lenguaje \Z, \z no coincide con un carácter \n al final de una cadena.Unlike the \Z language element, \z does not match a \n character at the end of a string. Por consiguiente, solo puede coincidir con la última línea de la cadena de entrada.Therefore, it can only match the last line of the input string.

En el ejemplo siguiente, se usa el delimitador \z en una expresión regular que por lo demás es idéntica al ejemplo de la sección anterior, que extrae información sobre los años durante los que existieron algunos equipos del béisbol profesionales.The following example uses the \z anchor in a regular expression that is otherwise identical to the example in the previous section, which extracts information about the years during which some professional baseball teams existed. En el ejemplo, se intenta buscar coincidencias con cada uno de los cinco elementos de una matriz de cadenas con el patrón de expresión regular ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z.The example tries to match each of five elements in a string array with the regular expression pattern ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z. Dos de las cadenas finalizan con caracteres de retorno de carro y salto de línea, una finaliza con un carácter de salto de línea, y dos no finalizan con un carácter de retorno de carro ni con un carácter de salto de línea.Two of the strings end with carriage return and line feed characters, one ends with a line feed character, and two end with neither a carriage return nor a line feed character. Como muestra la salida, solo coinciden con el patrón las cadenas sin un carácter de retorno de carro ni de salto de línea.As the output shows, only the strings without a carriage return or line feed character match the pattern.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] inputs = { "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957", 
                          "Chicago Cubs, National League, 1903-present" + Environment.NewLine,
                          "Detroit Tigers, American League, 1901-present\\r",
                          "New York Giants, National League, 1885-1957",
                          "Washington Senators, American League, 1901-1960" + Environment.NewLine };  
      string pattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z";

      foreach (string input in inputs)
      {
         if (input.Length > 70 || ! input.Contains(",")) continue;
         
         Console.WriteLine(Regex.Escape(input));
         Match match = Regex.Match(input, pattern);
         if (match.Success)
            Console.WriteLine("   Match succeeded.");
         else
            Console.WriteLine("   Match failed.");
      }   
   }
}
// The example displays the following output:
//    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
//       Match succeeded.
//    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
//       Match failed.
//    Detroit\ Tigers,\ American\ League,\ 1901-present\n
//       Match failed.
//    New\ York\ Giants,\ National\ League,\ 1885-1957
//       Match succeeded.
//    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
//       Match failed.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim inputs() As String = { "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",  _
                            "Chicago Cubs, National League, 1903-present" + vbCrLf, _
                            "Detroit Tigers, American League, 1901-present" + vbLf, _
                            "New York Giants, National League, 1885-1957", _
                            "Washington Senators, American League, 1901-1960" + vbCrLf }  
      Dim pattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z"

      For Each input As String In inputs
         If input.Length > 70 Or Not input.Contains(",") Then Continue For

         Console.WriteLine(Regex.Escape(input))
         Dim match As Match = Regex.Match(input, pattern)
         If match.Success Then
            Console.WriteLine("   Match succeeded.")
         Else
            Console.WriteLine("   Match failed.")
         End If
      Next   
   End Sub
End Module
' The example displays the following output:
'    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
'       Match succeeded.
'    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
'       Match failed.
'    Detroit\ Tigers,\ American\ League,\ 1901-present\n
'       Match failed.
'    New\ York\ Giants,\ National\ League,\ 1885-1957
'       Match succeeded.
'    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
'       Match failed.

Volver al principioBack to top

Coincidencias contiguas: \GContiguous Matches: \G

El delimitador \G especifica que debe producirse una coincidencia en el punto en el que finalizó la coincidencia anterior.The \G anchor specifies that a match must occur at the point where the previous match ended. El uso de este delimitador con el método Regex.Matches o Match.NextMatch permite asegurarse de que todas las coincidencias son contiguas.When you use this anchor with the Regex.Matches or Match.NextMatch method, it ensures that all matches are contiguous.

En el ejemplo siguiente se usa una expresión regular para extraer los nombres de especies de roedores de una cadena delimitada por comas.The following example uses a regular expression to extract the names of rodent species from a comma-delimited string.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "capybara,squirrel,chipmunk,porcupine,gopher," + 
                     "beaver,groundhog,hamster,guinea pig,gerbil," + 
                     "chinchilla,prairie dog,mouse,rat";
      string pattern = @"\G(\w+\s?\w*),?";
      Match match = Regex.Match(input, pattern);
      while (match.Success) 
      {
         Console.WriteLine(match.Groups[1].Value);
         match = match.NextMatch();
      } 
   }
}
// The example displays the following output:
//       capybara
//       squirrel
//       chipmunk
//       porcupine
//       gopher
//       beaver
//       groundhog
//       hamster
//       guinea pig
//       gerbil
//       chinchilla
//       prairie dog
//       mouse
//       rat
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "capybara,squirrel,chipmunk,porcupine,gopher," + _
                            "beaver,groundhog,hamster,guinea pig,gerbil," + _
                            "chinchilla,prairie dog,mouse,rat"
      Dim pattern As String = "\G(\w+\s?\w*),?"
      Dim match As Match = Regex.Match(input, pattern)
      Do While match.Success
         Console.WriteLine(match.Groups(1).Value)
         match = match.NextMatch()
      Loop 
   End Sub
End Module
' The example displays the following output:
'       capybara
'       squirrel
'       chipmunk
'       porcupine
'       gopher
'       beaver
'       groundhog
'       hamster
'       guinea pig
'       gerbil
'       chinchilla
'       prairie dog
'       mouse
'       rat

La expresión regular \G(\w+\s?\w*),? se interpreta como se muestra en la tabla siguiente.The regular expression \G(\w+\s?\w*),? is interpreted as shown in the following table.

ModeloPattern DescriptionDescription
\G Comienza donde finalizó la última coincidencia.Begin where the last match ended.
\w+ Buscar coincidencias con uno o más caracteres alfabéticos.Match one or more word characters.
\s? Coincide con cero o un espacio.Match zero or one space.
\w* Buscar una coincidencia con cero o más caracteres alfabéticos.Match zero or more word characters.
(\w+\s?\w*) Coincide con uno o varios caracteres que se usan para formar palabras seguidos de cero o un espacio, seguidos de cero o más caracteres que se usan para formar palabras.Match one or more word characters followed by zero or one space, followed by zero or more word characters. Este es el primer grupo de captura.This is the first capturing group.
,? Coincide con cero o un carácter de coma literal.Match zero or one occurrence of a literal comma character.

Volver al principioBack to top

Límite de palabras: \bWord Boundary: \b

El delimitador \b especifica que la coincidencia se debe producir en un límite entre un carácter que se usa para formar palabras (el elemento del lenguaje \w ) y un carácter que no se usa para formar palabras (el elemento del lenguaje \W ).The \b anchor specifies that the match must occur on a boundary between a word character (the \w language element) and a non-word character (the \W language element). Los caracteres que se usan para formar palabras son los caracteres alfanuméricos y de subrayado; un carácter que no se usa para formar palabras es cualquier carácter que no es alfanumérico ni de subrayado.Word characters consist of alphanumeric characters and underscores; a non-word character is any character that is not alphanumeric or an underscore. (Para más información, vea Clases de carácter). La coincidencia también se puede producir en un límite de palabras al principio o al final de la cadena.(For more information, see Character Classes.) The match may also occur on a word boundary at the beginning or end of the string.

El delimitador \b se usa con frecuencia para asegurarse de que una subexpresión coincide con una palabra completa en lugar de solo con el principio o el final de una palabra.The \b anchor is frequently used to ensure that a subexpression matches an entire word instead of just the beginning or end of a word. La expresión regular \bare\w*\b del ejemplo siguiente muestra este uso.The regular expression \bare\w*\b in the following example illustrates this usage. Coincide con cualquier palabra que comience por la subcadena "are".It matches any word that begins with the substring "are". El resultado del ejemplo también muestra que \b coincide tanto con el principio como con el final de la cadena de entrada.The output from the example also illustrates that \b matches both the beginning and the end of the input string.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "area bare arena mare";
      string pattern = @"\bare\w*\b";
      Console.WriteLine("Words that begin with 'are':");
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("'{0}' found at position {1}",
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//       Words that begin with 'are':
//       'area' found at position 0
//       'arena' found at position 10
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "area bare arena mare"
      Dim pattern As String = "\bare\w*\b"
      Console.WriteLine("Words that begin with 'are':")
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("'{0}' found at position {1}", _
                           match.Value, match.Index)
      Next
   End Sub
End Module
' The example displays the following output:
'       Words that begin with 'are':
'       'area' found at position 0
'       'arena' found at position 10

El patrón de la expresión regular se interpreta como se muestra en la tabla siguiente.The regular expression pattern is interpreted as shown in the following table.

ModeloPattern DescriptionDescription
\b Iniciar la búsqueda de coincidencias en un límite de palabras.Begin the match at a word boundary.
are Coincide con la subcadena "are".Match the substring "are".
\w* Buscar una coincidencia con cero o más caracteres alfabéticos.Match zero or more word characters.
\b Finalizar la búsqueda de coincidencias en un límite de palabras.End the match at a word boundary.

Volver al principioBack to top

Fuera de un límite de palabras: \BNon-Word Boundary: \B

El delimitador \B especifica que la coincidencia no se debe producir en un límite de palabras.The \B anchor specifies that the match must not occur on a word boundary. Es lo contrario del delimitador \b .It is the opposite of the \b anchor.

En el ejemplo siguiente, se usa el delimitador \B para buscar apariciones de la subcadena "qu" en una palabra.The following example uses the \B anchor to locate occurrences of the substring "qu" in a word. El patrón de expresión regular \Bqu\w+ coincide con una subcadena que comienza por "qu" que no está al principio de una palabra y que continúa hasta el final de la palabra.The regular expression pattern \Bqu\w+ matches a substring that begins with a "qu" that does not start a word and that continues to the end of the word.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "equity queen equip acquaint quiet";
      string pattern = @"\Bqu\w+";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("'{0}' found at position {1}", 
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//       'quity' found at position 1
//       'quip' found at position 14
//       'quaint' found at position 21
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "equity queen equip acquaint quiet"
      Dim pattern As String = "\Bqu\w+"
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("'{0}' found at position {1}", _
                           match.Value, match.Index)
      Next
   End Sub
End Module
' The example displays the following output:
'       'quity' found at position 1
'       'quip' found at position 14
'       'quaint' found at position 21

El patrón de la expresión regular se interpreta como se muestra en la tabla siguiente.The regular expression pattern is interpreted as shown in the following table.

ModeloPattern DescriptionDescription
\B La búsqueda de coincidencias no comienza en un límite de palabras.Do not begin the match at a word boundary.
qu Coincide con la subcadena "qu".Match the substring "qu".
\w+ Buscar coincidencias con uno o más caracteres alfabéticos.Match one or more word characters.

Vea tambiénSee Also

Lenguaje de expresiones regulares: referencia rápidaRegular Expression Language - Quick Reference
Opciones de expresiones regularesRegular Expression Options