Aracılığıyla paylaş


Normal ifade nesne modeli

Bu makalede, .NET normal ifadeleriyle çalışırken kullanılan nesne modeli açıklanmaktadır.

Normal ifade altyapısı

.NET'teki normal ifade altyapısı sınıfı tarafından Regex temsil edilir. Normal ifade altyapısı, bir normal ifadeyi ayrıştırıp derlemek ve bir giriş dizesiyle normal ifade deseniyle eşleşen işlemleri gerçekleştirmekle sorumludur. Altyapı, .NET normal ifade nesne modelindeki merkezi bileşendir.

Normal ifade altyapısını iki yoldan biriyle kullanabilirsiniz:

  • sınıfının statik yöntemlerini Regex çağırarak. Yöntem parametreleri giriş dizesini ve normal ifade desenini içerir. Normal ifade altyapısı statik yöntem çağrılarında kullanılan normal ifadeleri önbelleğe alır, bu nedenle aynı normal ifadeyi kullanan statik normal ifade yöntemlerine yapılan yinelenen çağrılar görece iyi bir performans sunar.

  • Bir Regex nesnenin örneğini oluşturarak, diğer bir ifadeyi sınıf oluşturucusunun normal ifadesine geçirerek. Bu durumda, Regex nesne sabittir (salt okunurdur) ve tek bir normal ifadeyle sıkı bir şekilde bağlanmış normal bir ifade altyapısını temsil eder. Örnekler tarafından Regex kullanılan normal ifadeler önbelleğe alınmadığından, aynı normal ifadeyle bir Regex nesnenin örneğini birden çok kez oluşturmamalısınız.

Aşağıdaki işlemleri gerçekleştirmek için sınıfının yöntemlerini Regex çağırabilirsiniz:

  • Bir dizenin normal ifade deseni ile eşleşip eşleşmediğini belirleyin.
  • Tek bir eşleşmeyi veya ilk eşleşmeyi ayıklayın.
  • Tüm eşleşmeleri ayıklayın.
  • Eşleşen bir alt dizeyi değiştirin.
  • Tek bir dizeyi dize dizisine bölün.

Bu işlemler aşağıdaki bölümlerde açıklanmıştır.

Normal ifade deseni eşleştirme

yöntemi, Regex.IsMatch dize desenle eşleşiyorsa veya false eşleşmiyorsa döndürürtrue. IsMatch yöntemi genellikle dize girişini doğrulamak için kullanılır. Örneğin, aşağıdaki kod bir dizenin Birleşik Devletler geçerli bir sosyal güvenlik numarasıyla eşleşmesini sağlar.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] values = { "111-22-3333", "111-2-3333"};
      string pattern = @"^\d{3}-\d{2}-\d{4}$";
      foreach (string value in values) {
         if (Regex.IsMatch(value, pattern))
            Console.WriteLine("{0} is a valid SSN.", value);
         else
            Console.WriteLine("{0}: Invalid", value);
      }
   }
}
// The example displays the following output:
//       111-22-3333 is a valid SSN.
//       111-2-3333: Invalid
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim values() As String = {"111-22-3333", "111-2-3333"}
        Dim pattern As String = "^\d{3}-\d{2}-\d{4}$"
        For Each value As String In values
            If Regex.IsMatch(value, pattern) Then
                Console.WriteLine("{0} is a valid SSN.", value)
            Else
                Console.WriteLine("{0}: Invalid", value)
            End If
        Next
    End Sub
End Module
' The example displays the following output:
'       111-22-3333 is a valid SSN.
'       111-2-3333: Invalid

Normal ifade düzeni ^\d{3}-\d{2}-\d{4}$ aşağıdaki tabloda gösterildiği gibi yorumlanır.

Desen Açıklama
^ Giriş dizesinin başlangıcıyla eşleş.
\d{3} Üç ondalık basamakla eşleş.
- Kısa çizgiyle eşleş.
\d{2} İki ondalık basamağı eşleştirin.
- Kısa çizgiyle eşleş.
\d{4} Dört ondalık basamağı eşleştirin.
$ Giriş dizesinin sonuyla eşleş.

Tek bir eşleşmeyi veya ilk eşleşmeyi ayıklama

yöntemi, Regex.Match normal ifade Match deseni ile eşleşen ilk alt dize hakkında bilgi içeren bir nesne döndürür. Match.Success özelliği bir eşleşme bulunduğunu belirten değerini döndürürsetrue, yöntemini çağırarak Match.NextMatch sonraki eşleşmeler hakkında bilgi alabilirsiniz. Bu yöntem çağrıları özelliği döndürene Match.Successfalsekadar devam edebilir. Örneğin, aşağıdaki kod bir dizede Regex.Match(String, String) yinelenen sözcüğün ilk oluşumunu bulmak için yöntemini kullanır. Daha sonra ek oluşumları bulmak için yöntemini çağırır Match.NextMatch . Örnek, geçerli eşleşmenin Match.Success başarılı olup olmadığını ve yönteme yönelik bir çağrının izlenip izlenmeyeceğini belirlemek için her yöntem çağrısından Match.NextMatch sonra özelliğini inceler.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle.";
      string pattern = @"\b(\w+)\W+(\1)\b";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("Duplicate '{0}' found at position {1}.",
                           match.Groups[1].Value, match.Groups[2].Index);
         match = match.NextMatch();
      }
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "This is a a farm that that raises dairy cattle."
        Dim pattern As String = "\b(\w+)\W+(\1)\b"
        Dim match As Match = Regex.Match(input, pattern)
        Do While match.Success
            Console.WriteLine("Duplicate '{0}' found at position {1}.", _
                              match.Groups(1).Value, match.Groups(2).Index)
            match = match.NextMatch()
        Loop
    End Sub
End Module
' The example displays the following output:
'       Duplicate 'a' found at position 10.
'       Duplicate 'that' found at position 22.

Normal ifade düzeni \b(\w+)\W+(\1)\b aşağıdaki tabloda gösterildiği gibi yorumlanır.

Desen Açıklama
\b Eşleşmeyi bir sözcük sınırında başlatın.
(\w+) Bir veya daha fazla sözcük karakteri eşleştir. Bu ilk yakalama grubudur.
\W+ Bir veya daha fazla sözcük olmayan karakter eşleştirin.
(\1) Yakalanan ilk dizeyi eşleştirin. Bu ikinci yakalama grubudur.
\b Eşleşmeyi bir sözcük sınırında sonlandırın.

Tüm eşleşmeleri ayıkla

yöntemi, Regex.Matches normal ifade altyapısının giriş dizesinde bulduğu tüm eşleşmeler hakkında bilgi içeren bir MatchCollection nesne döndürür. Örneğin, önceki örnek ve NextMatch yöntemleri yerine Match yöntemini çağırmak Matches için yeniden yazılabilir.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle.";
      string pattern = @"\b(\w+)\W+(\1)\b";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("Duplicate '{0}' found at position {1}.",
                           match.Groups[1].Value, match.Groups[2].Index);
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "This is a a farm that that raises dairy cattle."
        Dim pattern As String = "\b(\w+)\W+(\1)\b"
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("Duplicate '{0}' found at position {1}.", _
                              match.Groups(1).Value, match.Groups(2).Index)
        Next
    End Sub
End Module
' The example displays the following output:
'       Duplicate 'a' found at position 10.
'       Duplicate 'that' found at position 22.

Eşleşen alt dizeyi değiştirme

yöntemi, Regex.Replace normal ifade deseniyle eşleşen her alt dizeyi belirtilen bir dize veya normal ifade deseniyle değiştirir ve tüm giriş dizesini değiştirmelerle döndürür. Örneğin, aşağıdaki kod bir dizedeki ondalık sayıdan önce abd para birimi simgesi ekler.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+\.\d{2}\b";
      string replacement = "$$$&";
      string input = "Total Cost: 103.64";
      Console.WriteLine(Regex.Replace(input, pattern, replacement));
   }
}
// The example displays the following output:
//       Total Cost: $103.64
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\b\d+\.\d{2}\b"
        Dim replacement As String = "$$$&"
        Dim input As String = "Total Cost: 103.64"
        Console.WriteLine(Regex.Replace(input, pattern, replacement))
    End Sub
End Module
' The example displays the following output:
'       Total Cost: $103.64

Normal ifade düzeni \b\d+\.\d{2}\b aşağıdaki tabloda gösterildiği gibi yorumlanır.

Desen Açıklama
\b Bir sözcük sınırında eşleşmeye başla.
\d+ Bir veya daha fazla ondalık basamağı eşleştirin.
\. Bir dönemi eşleştirin.
\d{2} İki ondalık basamağı eşleştirin.
\b Eşlemeyi bir sözcük sınırında sonlandır.

Değiştirme düzeni $$$& aşağıdaki tabloda gösterildiği gibi yorumlanır.

Desen Değiştirme dizesi
$$ Dolar işareti ($) karakteri.
$& Eşleşen alt dizenin tamamı.

Tek bir dizeyi dize dizisine bölme

yöntemi, Regex.Split giriş dizesini normal ifade eşleşmesi tarafından tanımlanan konumlara böler. Örneğin, aşağıdaki kod numaralandırılmış bir listedeki öğeleri bir dize dizisine yerleştirir.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "1. Eggs 2. Bread 3. Milk 4. Coffee 5. Tea";
      string pattern = @"\b\d{1,2}\.\s";
      foreach (string item in Regex.Split(input, pattern))
      {
         if (! String.IsNullOrEmpty(item))
            Console.WriteLine(item);
      }
   }
}
// The example displays the following output:
//       Eggs
//       Bread
//       Milk
//       Coffee
//       Tea
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "1. Eggs 2. Bread 3. Milk 4. Coffee 5. Tea"
        Dim pattern As String = "\b\d{1,2}\.\s"
        For Each item As String In Regex.Split(input, pattern)
            If Not String.IsNullOrEmpty(item) Then
                Console.WriteLine(item)
            End If
        Next
    End Sub
End Module
' The example displays the following output:
'       Eggs
'       Bread
'       Milk
'       Coffee
'       Tea

Normal ifade düzeni \b\d{1,2}\.\s aşağıdaki tabloda gösterildiği gibi yorumlanır.

Desen Açıklama
\b Bir sözcük sınırında eşleşmeye başla.
\d{1,2} Bir veya iki ondalık basamağı eşleştirin.
\. Bir dönemi eşleştirin.
\s Bir boşluk karakteri ile eşleştirin.

MatchCollection ve Match nesneleri

Regex yöntemleri normal ifade nesne modelinin parçası olan iki nesne döndürür: MatchCollection nesnesi ve Match nesnesi.

Sınıfı MatchCollection

yöntemi, Regex.Matches normal ifade altyapısının bulduğu tüm eşleşmeleri giriş dizesinde bulundukları sırada temsil eden nesneler içeren Match bir MatchCollection nesne döndürür. Eşleşme yoksa, yöntemi üyesi olmayan bir MatchCollection nesne döndürür. özelliği, MatchCollection.Item[] koleksiyonun tek tek üyelerine dizine göre, sıfırdan özelliğin değerinden MatchCollection.Count bir küçüke kadar erişmenizi sağlar. Item[] , koleksiyonun dizin oluşturucu (C# dilinde) ve varsayılan özelliğidir (Visual Basic'te).

Varsayılan olarak, yöntemine Regex.Matches yapılan çağrı, nesneyi doldurmak MatchCollection için gecikmeli değerlendirme kullanır. ve MatchCollection.Item[] özellikleri gibi tam olarak doldurulmuş bir koleksiyon gerektiren özelliklere MatchCollection.Count erişim, bir performans cezası içerebilir. Sonuç olarak, yöntemi tarafından döndürülen nesnesini kullanarak IEnumerator koleksiyona MatchCollection.GetEnumerator erişmenizi öneririz. Tek tek diller, Visual Basic ve foreach C# gibi For Each koleksiyonun IEnumerator arabirimini sarmalayan yapılar sağlar.

Aşağıdaki örnek, bir nesneyi giriş MatchCollection dizesinde bulunan tüm eşleşmelerle doldurmak için yöntemini kullanırRegex.Matches(String). Örnek koleksiyonu numaralandırır, eşleşmeleri bir dize dizisine kopyalar ve karakter konumlarını bir tamsayı dizisine kaydeder.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
       MatchCollection matches;
       List<string> results = new List<string>();
       List<int> matchposition = new List<int>();

       // Create a new Regex object and define the regular expression.
       Regex r = new Regex("abc");
       // Use the Matches method to find all matches in the input string.
       matches = r.Matches("123abc4abcd");
       // Enumerate the collection to retrieve all matches and positions.
       foreach (Match match in matches)
       {
          // Add the match string to the string array.
           results.Add(match.Value);
           // Record the character position where the match was found.
           matchposition.Add(match.Index);
       }
       // List the results.
       for (int ctr = 0; ctr < results.Count; ctr++)
         Console.WriteLine("'{0}' found at position {1}.",
                           results[ctr], matchposition[ctr]);
   }
}
// The example displays the following output:
//       'abc' found at position 3.
//       'abc' found at position 7.
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim matches As MatchCollection
        Dim results As New List(Of String)
        Dim matchposition As New List(Of Integer)

        ' Create a new Regex object and define the regular expression.
        Dim r As New Regex("abc")
        ' Use the Matches method to find all matches in the input string.
        matches = r.Matches("123abc4abcd")
        ' Enumerate the collection to retrieve all matches and positions.
        For Each match As Match In matches
            ' Add the match string to the string array.
            results.Add(match.Value)
            ' Record the character position where the match was found.
            matchposition.Add(match.Index)
        Next
        ' List the results.
        For ctr As Integer = 0 To results.Count - 1
            Console.WriteLine("'{0}' found at position {1}.", _
                              results(ctr), matchposition(ctr))
        Next
    End Sub
End Module
' The example displays the following output:
'       'abc' found at position 3.
'       'abc' found at position 7.

Sınıfı Match

sınıfı, Match tek bir normal ifade eşleşmesinin sonucunu temsil eder. Nesnelere iki şekilde erişebilirsiniz Match :

  • bunları yöntemi tarafından Regex.Matches döndürülen nesneden MatchCollection alarak. Tek tek Match nesneleri almak için bir (C#içinde) veya For Each...Next (Visual Basic'te) yapısı kullanarak foreach koleksiyonu yineleyin veya dizine veya ada göre belirli Match bir nesneyi almak için özelliğini kullanınMatchCollection.Item[]. Ayrıca, koleksiyonu dizine göre yineleyerek koleksiyondaki nesne sayısının sıfırdan bire daha az olmasını sağlayarak tek tek Match nesneleri de alabilirsiniz. Ancak bu yöntem, özelliğine eriştiği için gecikmeli değerlendirmeden MatchCollection.Count yararlanmaz.

    Aşağıdaki örnek, veya For Each...Next yapısını kullanarak foreach koleksiyonu yineleyerek nesneden MatchCollection tek tek Match nesneleri alır. Normal ifade yalnızca giriş dizesindeki "abc" dizesiyle eşleşir.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "abc";
          string input = "abc123abc456abc789";
          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:
    //       abc found at position 0.
    //       abc found at position 6.
    //       abc found at position 12.
    
    Imports System.Text.RegularExpressions
    
    Module Example
        Public Sub Main()
            Dim pattern As String = "abc"
            Dim input As String = "abc123abc456abc789"
            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:
    '       abc found at position 0.
    '       abc found at position 6.
    '       abc found at position 12.
    
  • Bir dizedeki veya dizenin Regex.Match bir Match bölümündeki ilk eşleşmeyi temsil eden bir nesne döndüren yöntemini çağırarak. Özelliğin değerini Match.Success alarak eşleşmenin bulunup bulunmadığını belirleyebilirsiniz. Sonraki eşleşmeleri temsil eden nesneleri almak Match için, döndürülen Match nesnenin Match.NextMatch özelliği olana falsekadar Success yöntemini art arda çağırın.

    Aşağıdaki örnek, giriş dizesindeki Regex.Match(String, String) "abc" dizesiyle eşleştirmek için ve Match.NextMatch yöntemlerini kullanır.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "abc";
          string input = "abc123abc456abc789";
          Match match = Regex.Match(input, pattern);
          while (match.Success)
          {
             Console.WriteLine("{0} found at position {1}.",
                               match.Value, match.Index);
             match = match.NextMatch();
          }
       }
    }
    // The example displays the following output:
    //       abc found at position 0.
    //       abc found at position 6.
    //       abc found at position 12.
    
    Imports System.Text.RegularExpressions
    
    Module Example
        Public Sub Main()
            Dim pattern As String = "abc"
            Dim input As String = "abc123abc456abc789"
            Dim match As Match = Regex.Match(input, pattern)
            Do While match.Success
                Console.WriteLine("{0} found at position {1}.", _
                                  match.Value, match.Index)
                match = match.NextMatch()
            Loop
        End Sub
    End Module
    ' The example displays the following output:
    '       abc found at position 0.
    '       abc found at position 6.
    '       abc found at position 12.
    

Sınıfının iki özelliği Match koleksiyon nesneleri döndürür:

  • özelliği, Match.Groups normal ifade desenindeki yakalama gruplarıyla eşleşen alt dizeler hakkında bilgi içeren bir GroupCollection nesne döndürür.

  • Match.Captures özelliği sınırlı kullanımda olan bir CaptureCollection nesne döndürür. özelliği olan Successfalsebir Match nesne için koleksiyon doldurulmuyor. Aksi takdirde, nesneyle aynı bilgilere Match sahip tek Capture bir nesne içerir.

Bu nesneler hakkında daha fazla bilgi için bu makalenin devamında yer alan Sınıf GroupCollectionCaptureCollection ve Sınıf bölümleri bölümüne bakın.

sınıfının iki ek özelliği Match eşleşme hakkında bilgi sağlar. özelliği, Match.Value giriş dizesinde normal ifade deseni ile eşleşen alt dizeyi döndürür. özelliği, Match.Index giriş dizesindeki eşleşen dizenin sıfır tabanlı başlangıç konumunu döndürür.

Sınıfın Match iki desen eşleştirme yöntemi de vardır:

  • yöntemi, Match.NextMatch geçerli Match nesne tarafından temsil edilen eşleşmeden sonra eşleşmeyi bulur ve bu eşleşmeyi temsil eden bir Match nesne döndürür.

  • yöntemi, Match.Result eşleşen dizede belirtilen bir değiştirme işlemi gerçekleştirir ve sonucu döndürür.

Aşağıdaki örnek, iki kesirli basamak içeren her sayıdan önce bir $ simgesi ve boşluk eklemek için yöntemini kullanır Match.Result .

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+(,\d{3})*\.\d{2}\b";
      string input = "16.32\n194.03\n1,903,672.08";

      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine(match.Result("$$ $&"));
   }
}
// The example displays the following output:
//       $ 16.32
//       $ 194.03
//       $ 1,903,672.08
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\b\d+(,\d{3})*\.\d{2}\b"
        Dim input As String = "16.32" + vbCrLf + "194.03" + vbCrLf + "1,903,672.08"

        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine(match.Result("$$ $&"))
        Next
    End Sub
End Module
' The example displays the following output:
'       $ 16.32
'       $ 194.03
'       $ 1,903,672.08

Normal ifade deseni \b\d+(,\d{3})*\.\d{2}\b aşağıdaki tabloda gösterildiği gibi tanımlanır.

Desen Açıklama
\b Bir sözcük sınırında eşleşmeye başla.
\d+ Bir veya daha fazla ondalık basamağı eşleştirin.
(,\d{3})* Virgüllerin sıfır veya daha fazla oluşumunu ve ardından üç ondalık basamak eşleştirin.
\. Ondalık nokta karakteriyle eşleş.
\d{2} İki ondalık basamağı eşleştirin.
\b Eşlemeyi bir sözcük sınırında sonlandır.

Değiştirme düzeni $$ $& , eşleşen alt dizenin dolar işareti ($) simgesi (desen), boşluk ve eşleşme değeri ( $$$& desen) ile değiştirilmesi gerektiğini belirtir.

Sınıfı GroupCollection

özelliği, Match.Groups yakalanan grupları tek bir GroupCollection eşleşmede temsil eden nesneler içeren Group bir nesne döndürür. Koleksiyondaki ilk Group nesne (dizin 0'da) eşleşmenin tamamını temsil eder. Aşağıdaki her nesne tek bir yakalama grubunun sonuçlarını temsil eder.

özelliğini kullanarak GroupCollection.Item[] koleksiyondaki tek tek Group nesneleri alabilirsiniz. Adsız grupları koleksiyondaki sıralı konumlarına göre alabilir ve adlandırılmış grupları ada veya sıralı konuma göre alabilirsiniz. Adsız yakalamalar koleksiyonda ilk sırada görünür ve normal ifade deseninde göründükleri sırada soldan sağa dizinlenir. Adlandırılmış yakalamalar, adsız yakalamalardan sonra, normal ifade deseninde göründükleri sırayla soldan sağa dizinlenir. Belirli bir normal ifade eşleştirme yöntemi için döndürülen koleksiyonda hangi numaralı grupların kullanılabilir olduğunu belirlemek için örnek Regex.GetGroupNumbers yöntemini çağırabilirsiniz. Koleksiyonda hangi adlandırılmış grupların kullanılabilir olduğunu belirlemek için örnek Regex.GetGroupNames yöntemini çağırabilirsiniz. Her iki yöntem de herhangi bir normal ifade tarafından bulunan eşleşmeleri analiz eden genel amaçlı yordamlarda özellikle yararlıdır.

GroupCollection.Item[] özelliği, C# içindeki koleksiyonun dizin oluşturucusdur ve Visual Basic'te koleksiyon nesnesinin varsayılan özelliğidir. Bu, tek tek Group nesnelere dizinle (veya adlandırılmış gruplar söz konusu olduğunda ada göre) aşağıdaki gibi erişilebileceği anlamına gelir:

Group group = match.Groups[ctr];
Dim group As Group = match.Groups(ctr)

Aşağıdaki örnek, bir tarihin ayını, gününü ve yılını yakalamak için gruplandırma yapılarını kullanan normal bir ifadeyi tanımlar.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\w+)\s(\d{1,2}),\s(\d{4})\b";
      string input = "Born: July 28, 1989";
      Match match = Regex.Match(input, pattern);
      if (match.Success)
         for (int ctr = 0; ctr <  match.Groups.Count; ctr++)
            Console.WriteLine("Group {0}: {1}", ctr, match.Groups[ctr].Value);
    }
}
// The example displays the following output:
//       Group 0: July 28, 1989
//       Group 1: July
//       Group 2: 28
//       Group 3: 1989
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\b(\w+)\s(\d{1,2}),\s(\d{4})\b"
        Dim input As String = "Born: July 28, 1989"
        Dim match As Match = Regex.Match(input, pattern)
        If match.Success Then
            For ctr As Integer = 0 To match.Groups.Count - 1
                Console.WriteLine("Group {0}: {1}", ctr, match.Groups(ctr).Value)
            Next
        End If
    End Sub
End Module
' The example displays the following output:
'       Group 0: July 28, 1989
'       Group 1: July
'       Group 2: 28
'       Group 3: 1989

Normal ifade deseni \b(\w+)\s(\d{1,2}),\s(\d{4})\b aşağıdaki tabloda gösterildiği gibi tanımlanır.

Desen Açıklama
\b Bir sözcük sınırında eşleşmeye başla.
(\w+) Bir veya daha fazla sözcük karakteri eşleştir. Bu ilk yakalama grubudur.
\s Bir boşluk karakteri ile eşleştirin.
(\d{1,2}) Bir veya iki ondalık basamağı eşleştirin. Bu ikinci yakalama grubudur.
, Bir virgülü eşleştirin.
\s Bir boşluk karakteri ile eşleştirin.
(\d{4}) Dört ondalık basamağı eşleştirin. Bu, üçüncü yakalama grubudur.
\b Eşleşmeyi bir sözcük sınırında sonlandırın.

Yakalanan grup

sınıfı, Group tek bir yakalama grubunun sonucunu temsil eder. Normal ifadede tanımlanan yakalama gruplarını temsil eden grup nesneleri, özelliği tarafından döndürülen nesnenin GroupCollection özelliği tarafından Item[]Match.Groups döndürülür. Item[] özelliği, dizin oluşturucu (C#'da) ve sınıfın varsayılan özelliğidir (Visual Basic'te).Group Veya yapısını kullanarak foreachFor Each koleksiyonu yineleyerek tek tek üyeleri de alabilirsiniz. Bir örnek için önceki bölüme bakın.

Aşağıdaki örnek, alt dizeleri gruplar halinde yakalamak için iç içe gruplandırma yapılarını kullanır. Normal ifade deseni (a(b))c "abc" dizesiyle eşleşir. "ab" alt dizesini ilk yakalama grubuna, "b" alt dizesini de ikinci yakalama grubuna atar.

var matchposition = new List<int>();
var results = new List<string>();
// Define substrings abc, ab, b.
var r = new Regex("(a(b))c");
Match m = r.Match("abdabc");
for (int i = 0; m.Groups[i].Value != ""; i++)
{
    // Add groups to string array.
    results.Add(m.Groups[i].Value);
    // Record character position.
    matchposition.Add(m.Groups[i].Index);
}

// Display the capture groups.
for (int ctr = 0; ctr < results.Count; ctr++)
    Console.WriteLine("{0} at position {1}",
                      results[ctr], matchposition[ctr]);
// The example displays the following output:
//       abc at position 3
//       ab at position 3
//       b at position 4
Dim matchposition As New List(Of Integer)
Dim results As New List(Of String)
' Define substrings abc, ab, b.
Dim r As New Regex("(a(b))c")
Dim m As Match = r.Match("abdabc")
Dim i As Integer = 0
While Not (m.Groups(i).Value = "")
    ' Add groups to string array.
    results.Add(m.Groups(i).Value)
    ' Record character position. 
    matchposition.Add(m.Groups(i).Index)
    i += 1
End While

' Display the capture groups.
For ctr As Integer = 0 to results.Count - 1
    Console.WriteLine("{0} at position {1}", _
                      results(ctr), matchposition(ctr))
Next
' The example displays the following output:
'       abc at position 3
'       ab at position 3
'       b at position 4

Aşağıdaki örnek, normal ifadenin iki nokta üst üste (:)) böldüğü "DATANAME:VALUE" biçimindeki verileri içeren bir dizeden alt dizeleri yakalamak için adlandırılmış gruplandırma yapılarını kullanır.

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

Normal ifade deseni ^(?<name>\w+):(?<value>\w+) aşağıdaki tabloda gösterildiği gibi tanımlanır.

Desen Açıklama
^ Giriş dizesinin başında eşleşmeye başla.
(?<name>\w+) Bir veya daha fazla sözcük karakteri eşleştir. Bu yakalama grubunun adı şeklindedir name.
: İki nokta üst üste eşleştir.
(?<value>\w+) Bir veya daha fazla sözcük karakteri eşleştir. Bu yakalama grubunun adı şeklindedir value.

sınıfının özellikleri Group yakalanan grup hakkında bilgi sağlar: Group.Value özelliği yakalanan alt dizeyi içerir, Group.Index özelliği yakalanan grubun giriş metnindeki başlangıç konumunu, Group.Length özelliği yakalanan metnin uzunluğunu içerir ve Group.Success özelliği bir alt dizenin yakalama grubu tarafından tanımlanan desenle eşleşip eşleşmediğini gösterir.

Bir gruba niceleyici uygulama (daha fazla bilgi için bkz . Niceleyiciler), yakalama grubu başına bir yakalama ilişkisini iki şekilde değiştirir:

  • * Veya *? niceleyicisi (sıfır veya daha fazla eşleşme belirtir) bir gruba uygulanmışsa, bir yakalama grubunun giriş dizesinde eşleşmesi olmayabilir. Yakalanan metin olmadığında, nesnenin Group özellikleri aşağıdaki tabloda gösterildiği gibi ayarlanır.

    Group özelliği Değer
    Success false
    Value String.Empty
    Length 0

    Aşağıdaki örnek, bir gösterim sağlar. Normal ifade deseninde aaa(bbb)*ccc, ilk yakalama grubu ("bbb") sıfır veya daha fazla kez eşleştirilebilir. "aaaccc" giriş dizesi desenle eşleştiğinden, yakalama grubunun eşleşmesi yoktur.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "aaa(bbb)*ccc";
          string input = "aaaccc";
          Match match = Regex.Match(input, pattern);
          Console.WriteLine("Match value: {0}", match.Value);
          if (match.Groups[1].Success)
             Console.WriteLine("Group 1 value: {0}", match.Groups[1].Value);
          else
             Console.WriteLine("The first capturing group has no match.");
       }
    }
    // The example displays the following output:
    //       Match value: aaaccc
    //       The first capturing group has no match.
    
    Imports System.Text.RegularExpressions
    
    Module Example
        Public Sub Main()
            Dim pattern As String = "aaa(bbb)*ccc"
            Dim input As String = "aaaccc"
            Dim match As Match = Regex.Match(input, pattern)
            Console.WriteLine("Match value: {0}", match.Value)
            If match.Groups(1).Success Then
                Console.WriteLine("Group 1 value: {0}", match.Groups(1).Value)
            Else
                Console.WriteLine("The first capturing group has no match.")
            End If
        End Sub
    End Module
    ' The example displays the following output:
    '       Match value: aaaccc
    '       The first capturing group has no match.
    
  • Niceleyiciler, bir yakalama grubu tarafından tanımlanan bir desenin birden çok örneğini eşleştirebilir. Bu durumda, bir Group nesnenin Value ve Length özellikleri yalnızca yakalanan son alt dize hakkında bilgi içerir. Örneğin, aşağıdaki normal ifade nokta ile biten tek bir cümleyle eşleşir. İki gruplandırma yapısı kullanır: İlki bir boşluk karakteriyle birlikte tek tek sözcükleri yakalar; ikincisi tek tek sözcükleri yakalar. Örnekteki çıktıda gösterildiği gibi, normal ifade tümceyi yakalamada başarılı olsa da, ikinci yakalama grubu yalnızca son sözcüğü yakalar.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = @"\b((\w+)\s?)+\.";
          string input = "This is a sentence. This is another sentence.";
          Match match = Regex.Match(input, pattern);
          if (match.Success)
          {
             Console.WriteLine("Match: " + match.Value);
             Console.WriteLine("Group 2: " + match.Groups[2].Value);
          }
       }
    }
    // The example displays the following output:
    //       Match: This is a sentence.
    //       Group 2: sentence
    
    Imports System.Text.RegularExpressions
    
    Module Example
        Public Sub Main()
            Dim pattern As String = "\b((\w+)\s?)+\."
            Dim input As String = "This is a sentence. This is another sentence."
            Dim match As Match = Regex.Match(input, pattern)
            If match.Success Then
                Console.WriteLine("Match: " + match.Value)
                Console.WriteLine("Group 2: " + match.Groups(2).Value)
            End If
        End Sub
    End Module
    ' The example displays the following output:
    '       Match: This is a sentence.
    '       Group 2: sentence
    

Sınıfı CaptureCollection

Group nesnesi yalnızca son yakalama hakkında bilgi içerir. Ancak, bir yakalama grubu tarafından yapılan yakalama kümesinin tamamı, özelliği tarafından Group.Captures döndürülen nesneden CaptureCollection hala kullanılabilir. Koleksiyonun her üyesi, bu yakalama grubu tarafından yapılan yakalamayı, yakalandıkları sırayla (ve bu nedenle, yakalanan dizelerin giriş dizesinde soldan sağa eşleştirildiği sırada) temsil eden bir Capture nesnedir. Koleksiyondan tek tek Capture nesneleri iki yoldan biriyle alabilirsiniz:

  • (C#'de) veya For Each (Visual Basic'te) gibi foreach bir yapı kullanarak koleksiyonda yineleme yaparak.

  • dizine CaptureCollection.Item[] göre belirli bir nesneyi almak için özelliğini kullanarak. Item[] özelliği, nesnenin CaptureCollection varsayılan özelliğidir (Visual Basic'te) veya dizin oluşturucudur (C#'ta).

Bir niceleyici bir yakalama grubuna uygulanmazsa, CaptureCollection nesnesi nesnesiyle aynı eşleşme Group hakkında bilgi sağladığından çok az ilgi çekici olan tek Capture bir nesne içerir. Bir niceleyici bir yakalama grubuna uygulanırsa, CaptureCollection nesne yakalama grubu tarafından yapılan tüm yakalamaları içerir ve koleksiyonun son üyesi nesneyle aynı yakalamayı Group temsil eder.

Örneğin, "abcabcabc" dizesinden eşleşmeleri yakalamak için normal ifade desenini ((a(b))c)+ (burada + niceleyici bir veya daha fazla eşleşme belirtir) kullanırsanız, her Group nesnenin CaptureCollection nesnesi üç üye içerir.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "((a(b))c)+";
      string input = "abcabcabc";

      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Match: '{0}' at position {1}",
                           match.Value, match.Index);
         GroupCollection groups = match.Groups;
         for (int ctr = 0; ctr < groups.Count; ctr++) {
            Console.WriteLine("   Group {0}: '{1}' at position {2}",
                              ctr, groups[ctr].Value, groups[ctr].Index);
            CaptureCollection captures = groups[ctr].Captures;
            for (int ctr2 = 0; ctr2 < captures.Count; ctr2++) {
               Console.WriteLine("      Capture {0}: '{1}' at position {2}",
                                 ctr2, captures[ctr2].Value, captures[ctr2].Index);
            }
         }
      }
   }
}
// The example displays the following output:
//       Match: 'abcabcabc' at position 0
//          Group 0: 'abcabcabc' at position 0
//             Capture 0: 'abcabcabc' at position 0
//          Group 1: 'abc' at position 6
//             Capture 0: 'abc' at position 0
//             Capture 1: 'abc' at position 3
//             Capture 2: 'abc' at position 6
//          Group 2: 'ab' at position 6
//             Capture 0: 'ab' at position 0
//             Capture 1: 'ab' at position 3
//             Capture 2: 'ab' at position 6
//          Group 3: 'b' at position 7
//             Capture 0: 'b' at position 1
//             Capture 1: 'b' at position 4
//             Capture 2: 'b' at position 7
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "((a(b))c)+"
        Dim input As STring = "abcabcabc"

        Dim match As Match = Regex.Match(input, pattern)
        If match.Success Then
            Console.WriteLine("Match: '{0}' at position {1}", _
                              match.Value, match.Index)
            Dim groups As GroupCollection = match.Groups
            For ctr As Integer = 0 To groups.Count - 1
                Console.WriteLine("   Group {0}: '{1}' at position {2}", _
                                  ctr, groups(ctr).Value, groups(ctr).Index)
                Dim captures As CaptureCollection = groups(ctr).Captures
                For ctr2 As Integer = 0 To captures.Count - 1
                    Console.WriteLine("      Capture {0}: '{1}' at position {2}", _
                                      ctr2, captures(ctr2).Value, captures(ctr2).Index)
                Next
            Next
        End If
    End Sub
End Module
' The example displays the following output:
'       Match: 'abcabcabc' at position 0
'          Group 0: 'abcabcabc' at position 0
'             Capture 0: 'abcabcabc' at position 0
'          Group 1: 'abc' at position 6
'             Capture 0: 'abc' at position 0
'             Capture 1: 'abc' at position 3
'             Capture 2: 'abc' at position 6
'          Group 2: 'ab' at position 6
'             Capture 0: 'ab' at position 0
'             Capture 1: 'ab' at position 3
'             Capture 2: 'ab' at position 6
'          Group 3: 'b' at position 7
'             Capture 0: 'b' at position 1
'             Capture 1: 'b' at position 4
'             Capture 2: 'b' at position 7

Aşağıdaki örnek, "XYZAbcAbcXYZAbcAb" dizesindeki "Abc" dizesinin ardışık bir veya daha fazla çalıştırmasını bulmak için normal ifadeyi (Abc)+ kullanır. Örnek, yakalanan alt dizelerden oluşan birden çok grup döndürmek için özelliğinin kullanımını Group.Captures gösterir.

int counter;
Match m;
CaptureCollection cc;
GroupCollection gc;

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

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

// Loop through each group.
for (int i = 0; i < gc.Count; i++)
{
    cc = gc[i].Captures;
    counter = cc.Count;

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

    // Loop through each capture in the group.
    for (int ii = 0; ii < counter; ii++)
    {
        // Display the capture and its position.
        Console.WriteLine(cc[ii] + "   Starts at character " +
             cc[ii].Index);
    }
}
// The example displays the following output:
//       Captured groups = 2
//       Captures count = 1
//       AbcAbcAbc   Starts at character 3
//       Captures count = 3
//       Abc   Starts at character 3
//       Abc   Starts at character 6
//       Abc   Starts at character 9
Dim counter As Integer
Dim m As Match
Dim cc As CaptureCollection
Dim gc As GroupCollection

' Look for groupings of "Abc".
Dim r As New Regex("(Abc)+")
' Define the string to search.
m = r.Match("XYZAbcAbcAbcXYZAbcAb")
gc = m.Groups

' Display the number of groups.
Console.WriteLine("Captured groups = " & gc.Count.ToString())

' Loop through each group.
Dim i, ii As Integer
For i = 0 To gc.Count - 1
    cc = gc(i).Captures
    counter = cc.Count

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

    ' Loop through each capture in the group.            
    For ii = 0 To counter - 1
        ' Display the capture and its position.
        Console.WriteLine(cc(ii).ToString() _
            & "   Starts at character " & cc(ii).Index.ToString())
    Next ii
Next i
' The example displays the following output:
'       Captured groups = 2
'       Captures count = 1
'       AbcAbcAbc   Starts at character 3
'       Captures count = 3
'       Abc   Starts at character 3
'       Abc   Starts at character 6
'       Abc   Starts at character 9  

Sınıfı Capture

sınıfı, Capture tek bir alt ifade yakalamasının sonuçlarını içerir. Capture.Value özelliği eşleşen metni içerir ve Capture.Index özelliği, eşleşen alt dizenin başladığı giriş dizesinde sıfır tabanlı konumu gösterir.

Aşağıdaki örnek, seçili şehirlerin sıcaklığı için bir giriş dizesini ayrıştırmaktadır. Bir şehri ve sıcaklığını ayırmak için virgül (",") ve her şehrin verilerini ayırmak için noktalı virgül (";") kullanılır. Giriş dizesinin tamamı tek bir eşleşmeyi temsil eder. Dizeyi ayrıştırmak için kullanılan normal ifade deseninde ((\w+(\s\w+)*),(\d+);)+, şehir adı ikinci yakalama grubuna atanır ve sıcaklık dördüncü yakalama grubuna atanır.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;";
      string pattern = @"((\w+(\s\w+)*),(\d+);)+";
      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Current temperatures:");
         for (int ctr = 0; ctr < match.Groups[2].Captures.Count; ctr++)
            Console.WriteLine("{0,-20} {1,3}", match.Groups[2].Captures[ctr].Value,
                              match.Groups[4].Captures[ctr].Value);
      }
   }
}
// The example displays the following output:
//       Current temperatures:
//       Miami                 78
//       Chicago               62
//       New York              67
//       San Francisco         59
//       Seattle               58
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;"
        Dim pattern As String = "((\w+(\s\w+)*),(\d+);)+"
        Dim match As Match = Regex.Match(input, pattern)
        If match.Success Then
            Console.WriteLine("Current temperatures:")
            For ctr As Integer = 0 To match.Groups(2).Captures.Count - 1
                Console.WriteLine("{0,-20} {1,3}", match.Groups(2).Captures(ctr).Value, _
                                  match.Groups(4).Captures(ctr).Value)
            Next
        End If
    End Sub
End Module
' The example displays the following output:
'       Current temperatures:
'       Miami                 78
'       Chicago               62
'       New York              67
'       San Francisco         59
'       Seattle               58

Normal ifade aşağıdaki tabloda gösterildiği gibi tanımlanır.

Desen Açıklama
\w+ Bir veya daha fazla sözcük karakteri eşleştir.
(\s\w+)* Boşluk karakterinin sıfır veya daha fazla tekrarını ve ardından bir veya daha fazla sözcük karakterini eşleştirin. Bu desen, çok sözcüklü şehir adlarla eşleşir. Bu, üçüncü yakalama grubudur.
(\w+(\s\w+)*) Boşluk karakterinin ve bir veya daha fazla sözcük karakterinin sıfır veya daha fazla tekrarının ardından gelen bir veya daha fazla sözcük karakterini eşleştirin. Bu ikinci yakalama grubudur.
, Bir virgülü eşleştirin.
(\d+) Bir veya daha fazla basamak eşleştirin. Bu dördüncü yakalama grubudur.
; Noktalı virgülle eşleştirin.
((\w+(\s\w+)*),(\d+);)+ Bir sözcüğün desenini ve ardından bir veya daha fazla virgül, bir veya daha fazla basamak ve noktalı virgül eklenerek bir veya daha fazla kez eşleştirin. Bu ilk yakalama grubudur.

Ayrıca bkz.