Привязки в регулярных выражениях

Привязки или атомарные утверждения нулевой ширины задают позицию в строке, в которой должно обнаруживаться соответствие. При использовании привязки в выражении поиска обработчик регулярных выражений не проходит по строке и не извлекает символы; он ищет совпадение только в указанной позиции. Например, ^ указывает, что совпадение должно начинаться в начале строки. Таким образом, регулярное выражение ^http: соответствует "http:" только в том случае, когда это соответствие обнаруживается в начале строки. В следующей таблице перечислены привязки, поддерживаемые регулярными выражениями на платформе .NET Framework.

Привязка

Описание

^

Соответствие должно находиться в начале строки или подстроки. Дополнительные сведения см. в разделе В начале строки.

$

Соответствие должно находиться в конце строки или до символа \n в конце строки. Дополнительные сведения см. в разделе В конце строки.

\A

Соответствие может находиться только в начале строки (многострочность не поддерживается). Дополнительные сведения см. в разделе Только в начале строки.

\Z

Соответствие должно находиться в конце строки или до символа \n в конце строки. Дополнительные сведения см. в разделе В конце строки или до конца новой строки.

\z

Соответствие должно находиться только в конце строки. Дополнительные сведения см. в разделе Только в конце строки.

\G

Соответствие должно начинаться в той точке, где заканчивается предыдущее соответствие. Дополнительные сведения см. в разделе Непрерывные соответствия.

\b

Соответствие должно находиться на границе слова. Дополнительные сведения см. в разделе Граница слова.

\B

Соответствие не должно находиться на границе слова. Дополнительные сведения см. в разделе Граница, не являющаяся границей слова.

Начало строки: ^

Привязка ^ указывает, что следующий шаблон должен начинаться в позиции первого символа строки. При использовании ^ с параметром RegexOptions.Multiline (см. раздел Параметры регулярных выражений) соответствие должно находиться в начале каждой строки.

В следующем примере в регулярном выражении используется привязка ^ для извлечения сведений о годах, в течение которых существовали некоторые профессиональные бейсбольные команды. В примере вызываются две перегрузки метода Regex.Matches():

  • Вызов перегрузки Matches(String, String) обнаруживает только первую подстроку в входной строке, которая соответствует шаблону регулярного выражения.

  • Вызов перегрузки Matches(String, String, RegexOptions) с параметром options, имеющим значение RegexOptions.Multiline, обнаруживает все пять подстрок.

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.
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.

Возможные интерпретации шаблона регулярного выражения ^((\w+(\s*)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))*,*)+ определены в следующей таблице.

Шаблон

Описание

^

Соответствие должно обнаруживаться в начале строки ввода (или в начале строки, если метод был вызван с параметром RegexOptions.Multiline).

((\w+(\s*)){2,}

Соответствует одному или нескольким буквенным символам, за которыми следует либо ноль, либо один пробел ровно два раза. Это первая группа записи. Это выражение также определяет вторую и третью группу записи: вторая состоит из записанного слова, а третья состоит из записанных пробелов.

,\s

Соответствует запятой (,), за которой следует пробел.

(\w+\s\w+)

Соответствует одному или нескольким буквенным символам, за которыми следует пробел и один или несколько буквенных символов. Это четвертая группа записи.

,

Совпадение с запятой.

\s\d{4}

Соответствует пробелу, за которым следуют четыре десятичных знака.

(-(\d{4}|present))*

Соответствует ни одному или одному вхождению дефиса, за которым следуют четыре десятичные цифры или строка "present". Это шестая группа записи. Он также включает седьмую захваченную группу.

,*

Соответствует ни одному или одному вхождению запятой.

(\s\d{4}(-(\d{4}|present))*,*)+

Соответствует одному или нескольким вхождениям следующих символов: пробела, четырех десятичных цифр, ноля или одного дефиса, за которым следуют четыре десятичные цифры или строки "present", и ноля или одной запятой. Это пятая группа записи.

К началу

Конец строки: $

Привязка $ указывает, что предыдущий шаблон должен обнаруживаться в конце входной строки или перед \n в конце входной строки.

Если $ используется с параметром RegexOptions.Multiline, соответствие может также обнаруживаться в конце строки. Следует отметить, что $ соответствует \n, но не соответствует \r\n (сочетание символов возврата каретки и новой строки, или CR/LF). Чтобы сопоставить комбинацию символов CR/LF, следует включить \r?$ в шаблон регулярного выражения.

В следующем примере в шаблон регулярного выражения, используемый в примере раздела Начало строки, добавляется привязка $. При использовании с исходной входной строкой, которая включает пять строк текста, методу Regex.Matches(String, String) не удается найти соответствие, поскольку конец первой строки не соответствует шаблону $. Когда исходная входная строка делится на массив строк, метод Regex.Matches(String, String) успешно сопоставляет все пять строк. При вызове метода Regex.Matches(String, String, RegexOptions) со значением параметра options, равным RegexOptions.Multiline, совпадения не обнаруживаются, поскольку шаблон регулярного выражения не учитывает символ возврата каретки (\u+000D). Однако при изменении шаблона регулярного выражения путем замены $ на \r?$ вызов метода Regex.Matches(String, String, RegexOptions) с параметром options, имеющим значение RegexOptions.Multiline, снова находит пять совпадений.

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.
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.

К началу

Только начало строки: \A

Привязка \A указывает, что совпадение должно находиться в начале входной строки. Он идентичен привязке ^ за исключением того, что \A игнорирует параметр RegexOptions.Multiline. Таким образом, соответствие может находиться только в начале первой строки многострочной входной строки.

Следующий пример похож на примеры для привязки ^ и $. Он использует привязку \A в регулярном выражении для извлечения сведений о годах, в течение которых существовали некоторые профессиональные бейсбольные команды. Входная строка включает пять строк. Вызов метода Regex.Matches(String, String, RegexOptions) обнаруживает только первую подстроку в входной строке, которая соответствует шаблону регулярного выражения. Как показано в примере, параметр Multiline не действует.

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.
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.

К началу

Конец строки или до начала новой строки: \Z

Привязка \Z указывает, что соответствие должно обнаруживаться в конце входной строки или перед \n в конце входной строки. Он идентичен привязке $ за исключением того, что \Z игнорирует параметр RegexOptions.Multiline. Таким образом, в многострочной строке соответствие может быть только в конце последней строки или в последней строке перед символом \n.

Следует отметить, что \Z соответствует \n, но не соответствует \r\n (комбинации символов CR/LF). Чтобы сопоставить CR/LF, включите \r?\Z в шаблон регулярных выражений.

В следующем примере в регулярном выражении, которое идентично примеру в разделе Начало строки, используется привязка \Z для извлечения сведений о годах, в течение которых существовали некоторые профессиональные бейсбольные команды. Часть выражения \r?\Z в регулярном выражении ^((\w+(\s*)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))*,*)+\r?\Z соответствует концу строки и соответствует строке, оканчивающейся на \n или \r\n. В результате каждый элемент в массиве соответствует шаблону регулярного выражения.

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.
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.

К началу

Конец строки только: \z

Привязка \z указывает, что совпадение должно обнаруживаться в конце строки ввода. Как и элемент языка $, \z игнорирует параметр RegexOptions.Multiline. В отличие от элемента языка \Z, \z не соответствует символу \n в конце строки. Таким образом, соответствие может находиться только в последней строке входной строки.

В следующем примере в регулярном выражении, которое идентично примеру в предыдущем разделе, используется привязка \z для извлечения сведений о годах, в течение которых существовали некоторые профессиональные бейсбольные команды. В примере выполняется попытка сопоставления каждого из пяти элементов в массиве строк с шаблоном регулярного выражения ^((\w+(\s*)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))*,*)+\r?\z. Два конца строки с символами возврата каретки и перевода строки, один заканчивается символом перевода строки, а второй не заканчивается ни символом возврата каретки, ни символом перевода строки. Как показывают выходные данные, шаблону соответствуют только строки, в которых отсутствует символ возврата каретки или символ перевода строки.

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.
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.

К началу

Непрерывные совпадения: \G

Привязка \G указывает, что соответствие должно обнаруживаться в той точке, где заканчивается предыдущее соответствие. При использовании этой привязки с методом Regex.Matches или Match.NextMatch гарантируется последовательность всех совпадений.

В следующем примере используется регулярное выражение для извлечения имен видов грызунов из строк с запятыми в качестве разделителей.

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

Возможные интерпретации регулярного выражения \G(\w+\s?\w*),? показаны в следующей таблице.

Шаблон

Описание

\G

Начать, где заканчивается последнее соответствие.

\w+

Совпадение с одним или несколькими символами слова.

\s?

Соответствует отсутствию пробела или вхождению пробела один раз.

\w*

Соответствует нулевому или большему числу буквенных символов.

(\w+\s? \w*)

Соответствует одному или нескольким буквенным символам, за которыми следует ноль или один пробел, а дальше ноль или несколько буквенных символов. Это первая группа записи.

,?

Соответствует ни одному или одному вхождению литерального символа запятой.

К началу

Граница слова: \b

Привязка \b указывает, что совпадение должно обнаруживаться на границе между буквенным символом (элемент языка \w) и символом, не являющимся буквенным (элемент языка \W). Символы слов — это буквенно-цифровые символы и знаки подчеркивания; все прочие символы не являются символами слов. (Дополнительные сведения см. в разделе Классы знаков.) Соответствие может также находиться на границе слова в начале или конце строки.

Привязка \b часто используются для того, чтобы гарантировать соответствие части выражения всему слову, а не началу или концу слова. Регулярное выражение \bare\w*\b в следующем примере иллюстрирует данное использование. Он соответствует любому слову, начинающемуся с подстроки "are". Выходные данные в примере также показывают, что \b соответствует как началу, так и концу входной строки.

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

В следующей таблице показаны возможные интерпретации этого шаблона регулярного выражения.

Шаблон

Описание

\b

Совпадение должно начинаться на границе слова.

are

Соответствует подстроке "are".

\w*

Соответствует нулевому или большему числу буквенных символов.

\b

Совпадение должно заканчиваться на границе слова.

К началу

Граница, не являющаяся границей слова: \B

Привязка \B указывает, что соответствие не должно обнаруживаться на границе слова. Является противоположностью объекта привязки \b.

В следующем примере используется привязка \B для обнаружения экземпляров подстроки "qu" в слове. Шаблон регулярного выражения \Bqu\w+ соответствует подстроке, которая начинается с "qu", не находится в начале слова, но продолжается до конца слова.

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

В следующей таблице показаны возможные интерпретации этого шаблона регулярного выражения.

Шаблон

Описание

\B

Соответствие не должно обнаруживаться на границе слова.

qu

Соответствует подстроке "qu".

\w+

Совпадение с одним или несколькими символами слова.

К началу

См. также

Ссылки

Параметры регулярных выражений

Основные понятия

Элементы языка регулярных выражений