Normal ifade nesne modeli

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

Düzenli ifade motoru

.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. Motor, .NET düzenli ifade nesne modelindeki merkezi bileşendir.

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

  • Regex sınıfının statik metotlarını ç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 düzenli ifadeyle sıkı bir şekilde bağlanmış düzenli ifade motorunu temsil eder. Regex örnekleri tarafından kullanılan normal ifadeler önbelleğe alınmadığından, aynı normal ifadeyle bir Regex nesnesini birden fazla 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

Regex.IsMatch yöntemi, dize desenle eşleşiyorsa true döndürür, eşleşmiyorsa false döndürür. 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($"{value} is a valid SSN.");
         else
            Console.WriteLine($"{value}: Invalid");
      }
   }
}
// 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 basamağı eşleştir.
- Bir kısa çizgiyle eşleştir.
\d{2} İki ondalık basamağı eşleştirin.
- Bir kısa çizgiyi eşleştir.
\d{4} Dört ondalık basamağı eşleştirin.
$ Giriş dizesinin sonuyla eşleş.

Tek bir eşleşme veya ilk eşleşmeyi bulma

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ı, Match.Success özelliği false döndürene kadar 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 Match.NextMatch yöntemini, ek oluşumları bulmak için çağırır. Her yöntem çağrısından sonra Match.Success özelliğini inceleyen örnek, mevcut eşleşmenin başarılı olup olmadığını ve Match.NextMatch yöntemine yönelik bir çağrının izlenip izlenmeyeceğini belirler.

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 '{match.Groups[1].Value}' found at position {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 kelime 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 Match ve NextMatch yöntemleri yerine Matches yöntemini çağıracak şekilde 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 '{match.Groups[1].Value}' found at position {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ştir

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şleşmeyi bir kelime 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.

Bu MatchCollection sınıfı

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

Varsayılan olarak, Regex.Matches yöntemine yapılan çağrı, MatchCollection nesnesini doldurmak için gecikmeli değerlendirme kullanır. Özelliklere, örneğin MatchCollection.Count ve MatchCollection.Item[] gibi tam olarak doldurulmuş bir koleksiyon gerektiren özelliklere erişim, bir performans cezasına yol açabilir. Sonuç olarak, MatchCollection.GetEnumerator yöntemi tarafından döndürülen IEnumerator nesnesini kullanarak koleksiyona erişmenizi öneririz. Bireysel diller, Visual Basic'teki For Each ve C#'taki foreach gibi koleksiyonun IEnumerator arabirimini saran yapılar sunar.

Aşağıdaki örnek, giriş dizgisinde bulunan tüm eşleşmelerle bir MatchCollection nesnesini doldurmak için Regex.Matches(String) yöntemini kullanır. Ö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($"'{results[ctr]}' found at position {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.

Bu Match sınıfı

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

  • MatchCollection yöntemi tarafından döndürülen nesneden Regex.Matches alınarak bunlar elde edilir. Tek tek Match nesneleri almak için, C# dilindeki foreach veya Visual Basic'teki For Each...Next yapısını kullanarak koleksiyonu yineleyin ya da belirli bir MatchCollection.Item[] nesnesini dizine veya ada göre almak için Match özelliğini kullanın. 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, MatchCollection.Count özelliğine eriştiği için gecikmeli değerlendirmeden yararlanmaz.

    Aşağıdaki örnek, MatchCollection nesnesinden tek tek Match nesnelerini almak için foreach veya For Each...Next yapısı kullanılarak koleksiyonun yinelemeyle nasıl yapıldığını gösterir. 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($"{match.Value} found at position {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 bir bölümündeki ilk eşleşmeyi temsil eden bir Match nesnesi döndüren Regex.Match yöntemini çağırarak. Özelliğin değerini Match.Success alarak eşleşmenin bulunup bulunmadığını belirleyebilirsiniz. Sonraki eşleşmeleri temsil eden Match nesneleri almak için, döndürülen Match nesnesinin Success özelliği false olana kadar Match.NextMatch yöntemini tekrar tekrar çağırın.

    Aşağıdaki örnek, giriş dizesindeki "abc" dizesiyle eşleştirmek için Regex.Match(String, String) 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($"{match.Value} found at position {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. Success özelliği false olan bir Match nesne için koleksiyon doldurulmamaktadır. Aksi halde, Capture nesnesi ile aynı bilgilere sahip tek bir Match nesnesi içerir.

Bu nesneler hakkında daha fazla bilgi için bu makalenin devamında yer alan Sınıf GroupCollection ve CaptureCollection 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 Match.Result yöntemini kullanır.

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şmeyi başlat.
\d+ Bir veya daha fazla ondalık basamağı eşleştirin.
(,\d{3})* Virgülden sonra gelen üç ondalık basamağın sıfır veya daha fazla tekrarını eşleştirin.
\. Ondalık nokta karakteriyle eşleştir.
\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.

Bu GroupCollection sınıfı

Match.Groups özelliği, tek bir GroupCollection eşleşmede yakalanan grupları temsil eden Group nesneleri içeren 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.

Koleksiyondaki GroupCollection.Item[] nesneleri, Group özelliğini kullanarak tek tek 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 {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 kelime 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. Item[] özelliğine sahip nesne tarafından döndürülen GroupCollection özelliği, bir normal ifadede tanımlanan yakalama gruplarını temsil eden grup nesnelerini döndürür. Item[] özelliği, dizin oluşturucu (C#'da) ve sınıfın varsayılan özelliğidir (Visual Basic'te).Group foreach veya For Each yapısını kullanarak koleksiyonu yineleyerek tek tek üyeleri 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($"{results[ctr]} at position {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ı name.
: Nokta ile eşleştir.
(?<value>\w+) Bir veya daha fazla sözcük karakteri eşleştir. Bu yakalama grubunun adı value'dir.

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 grubunda eşleşen bir kısım bulunmamaktadır.

    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: {match.Value}");
          if (match.Groups[1].Success)
             Console.WriteLine($"Group 1 value: {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 Value nesnenin Length ve Group ö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
    

Bu CaptureCollection sınıfı

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 CaptureCollection döndürülen nesneden Group.Captures 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 foreach veya Visual Basic'te For Each gibi bir yapı kullanarak koleksiyonda yineleme yapın.

  • CaptureCollection.Item[] özelliğini kullanarak indekse göre belirli bir nesneyi almak. 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, Group nesnesiyle aynı eşleşme bilgilerini sağladığı için pek ilgi çekici olmayan tek bir Capture nesnesi 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 CaptureCollection nesnenin Group 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: '{match.Value}' at position {match.Index}");
         GroupCollection groups = match.Groups;
         for (int ctr = 0; ctr < groups.Count; ctr++) {
            Console.WriteLine($"   Group {ctr}: '{groups[ctr].Value}' at position {groups[ctr].Index}");
            CaptureCollection captures = groups[ctr].Captures;
            for (int ctr2 = 0; ctr2 < captures.Count; ctr2++) {
               Console.WriteLine($"      Capture {ctr2}: '{captures[ctr2].Value}' at position {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, "XYZAbcAbcAbcXYZAbcAb" dizesinde "Abc" dizesinin bir veya daha fazla ardışık tekrarını bulmak için normal ifadeyi (Abc)+ kullanır. Örnek, Group.Captures özelliğinin, yakalanan alt dizelerden oluşan birden çok grubu iade etmek için nasıl kullanıldığını 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  

Bu Capture sınıfı

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 adlarıyla eşleşir. Bu, üçüncü yakalama grubudur.
(\w+(\s\w+)*) Bir veya daha fazla sözcük karakterini, ardından gelen sıfır veya daha fazla boşluk ve bir veya daha fazla sözcük karakteri ile 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ülü yakalayın.
((\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.