다음을 통해 공유


정규식의 앵커

앵커 또는 원자 너비가 0인 어설션에 일치가 발생해야 하는 문자열 내의 위치를 지정합니다. 검색 식에서 앵커를 사용할 때 정규식 엔진은 문자열을 통해 이동하거나 문자를 사용하지 않습니다. 지정한 위치에서만 일치 항목을 찾습니다. 예를 들어, ^은 일치 항목이 줄 또는 문자열의 시작 부분에서 시작해야 함을 지정합니다. 따라서 정규식 ^http:는 줄의 시작 부분에 있을 경우에만 "http:"를 일치시킵니다. 다음 표에서는 .NET Framework의 정규식에서 지원되는 앵커를 나열합니다.

앵커

설명

^

일치 항목이 문자열 또는 줄의 시작 부분에 있어야 합니다. 자세한 내용은 문자열 또는 선의 시작을 참조하십시오.

$

일치 항목이 문자열이나 선의 끝 또는 문자열이나 선의 끝에 있는 \n 앞에 있어야 합니다. 자세한 내용은 문자열 또는 선 끝을 참조하십시오.

\A

일치 항목이 문자열 시작 부분에만 있어야 합니다(여러 줄을 지원하지 않음). 자세한 내용은 문자열의 시작만을 참조하십시오.

\Z

일치 항목이 문자열의 끝이나 문자열의 끝에 있는 \n 앞에 있어야 합니다. 자세한 내용은 문자열의 끝 또는 줄 바꿈 종료 전을 참조하십시오.

\z

일치 항목이 문자열의 끝에만 있어야 합니다. 자세한 내용은 문자열의 끝만을 참조하십시오.

\G

일치 항목이 이전 일치 항목 찾기가 끝난 지점에서 시작해야 합니다. 자세한 내용은 연속 일치를 참조하십시오.

\b

일치 항목이 단어 경계에 있어야 합니다. 자세한 내용은 단어 경계를 참조하십시오.

\B

일치 항목이 단어 경계에 있어서는 안 됩니다. 자세한 내용은 비단어 경계를 참조하십시오.

문자열 또는 선 시작: ^

^ 앵커는 다음 패턴이 문자열의 첫 단어 위치에서 시작해야 한다고 지정합니다. ^를 RegexOptions.Multiline 옵션과 함께 사용할 경우(정규식 옵션 참조) 일치하는 내용을 각 줄 시작 부분에서 찾아야 합니다.

다음 예제에서는 몇몇 프로 야구 팀이 있었던 연도에 대한 정보를 추출하는 정규식에서 ^ 앵커를 사용합니다. 이 예제에서는 Regex.Matches() 메서드의 두 오버로드를 호출합니다.

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

하나 이상의 단어 문자 뒤에 0 또는 공백 하나를 정확히 두 번 일치시킵니다. 이 그룹은 첫 번째 캡처링 그룹입니다. 또한 이 식은 두 번째와 세 번째 캡처링 그룹을 정의합니다. 두 번째는 캡처된 단어, 세 번째는 캡처된 공백으로 구성됩니다.

,\s

쉼표 뒤에 공백 문자를 일치시킵니다.

(\w+\s\w+)

하나 이상의 단어 뒤에 공백, 그 뒤에 하나 이상의 단어 문자를 일치시킵니다. 이 그룹은 네 번째 캡처링 그룹입니다.

,

쉼표를 찾습니다.

\s\d{4}

공백 뒤에 네 개의 십진수를 일치시킵니다.

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

0개 또는 한 개의 하이픈 뒤에 4개의 10진수 또는 문자열 "present"를 일치시킵니다. 이 그룹은 여섯 번째 캡처링 그룹입니다. 또한 7번째 캡처 그룹도 포함되어 있습니다.

,*

0개 또는 한 개의 발견되는 쉼표를 일치시킵니다.

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

공백, 4개의 십진수, 0개 또는 한 개의 하이픈, 그 뒤에 4개의 십진수 또는 문자열 "present" 및 9개 또는 한 개의 쉼표 중 하나 이상 일치하는 항목을 찾습니다. 이 그룹은 다섯 번째 캡처링 그룹입니다.

맨 위로 이동

문자열 또는 선 끝: $

$ 앵커는 이전 패턴이 입력 문자열 끝에 있거나 입력 문자열 끝의 \n 앞에 있어야 한다고 지정합니다.

$를 RegexOptions.Multiline 옵션과 함께 사용하면 일치하는 내용을 줄 끝에서 찾을 수도 있습니다. $가 \n과 일치하지만 \r\n과는 일치하지 않습니다(캐리지 리턴과 줄 바꿈 문자 또는 CR/LF의 조합). CR/LF 문자 조합을 찾으려면 정규식 패턴에 \r?$를 포함합니다.

다음 예제에서는 $ 앵커를 문자열 또는 선의 시작 섹션에 나오는 예제에 사용되는 정규식 패턴에 추가합니다. 텍스트 5줄을 포함하는 원래 입력 문자열에 사용되면 Regex.Matches(String, String) 메서드는 첫 줄의 끝이 $ 패턴과 일치하지 않기 때문에 일치 항목을 찾을 수 없습니다. 원래 입력 문자열이 문자열 배열로 분할되면 Regex.Matches(String, String) 메서드는 각각 5줄에서 일치합니다. Regex.Matches(String, String, RegexOptions) 메서드가 options 매개 변수를 RegexOptions.Multiline으로 설정하여 호출되면 정규식 패턴이 캐리지 리턴 요소(\u+000D)를 고려하지 않기 때문에 일치 항목이 발견되지 않습니다. 그러나 $를 \r?$로 교체하고 options 매개 변수를 RegexOptions.Multiline으로 설정한 상태에서 Regex.Matches(String, String, RegexOptions) 메서드를 호출하여 정규식 패턴을 수정하면 다시 5개의 일치 항목을 찾습니다.

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 앵커를 사용합니다. 정규 식 ^((\w+(\s*)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))*,*)+\r?\Z의 \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?

0개 또는 한 개의 공백을 일치시킵니다.

\w*

0개 이상의 단어 문자를 일치시킵니다.

(\w+\s? \w*)

하나 이상의 단어 문자, 그 뒤에 0개 또는 한 개의 공백, 0개 이상의 단어 문자를 찾습니다. 이 그룹은 첫 번째 캡처링 그룹입니다.

,?

리터럴 쉼표 문자 0개 또는 한 개를 일치시킵니다.

맨 위로 이동

단어 경계: \b

\b 앵커는 일치 항목이 단어 문자(\w 언어 요소)와 비단어 문자(\W 언어 요소) 사이의 경계에 있어야 함을 지정합니다. 단어 문자는 영숫자 문자와 밑줄로 구성되며 비단어 문자는 영숫자나 밑줄이 아닌 모든 문자입니다. 자세한 내용은 문자 클래스을 참조하십시오. 일치 항목이 문자열 시작 또는 끝의 단어 경계에 있을 수도 있습니다.

\b 앵커는 단어 시작이나 끝에서 시작하는 대신 하위 식이 전체 단어와 일치하는지 확인하기 위해 자주 사용됩니다. 다음 예제의 정규식 \bare\w*\b는 이러한 사용을 보여 줍니다. "는" 부분 문자열로 시작하는 단어를 찾습니다. 예제의 출력은 \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*

0개 이상의 단어 문자를 일치시킵니다.

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

둘 이상의 단어 문자를 찾습니다.

맨 위로 이동

참고 항목

참조

정규식 옵션

개념

정규식 언어 요소