Model Objek Regex

Topik ini menjelaskan model objek yang digunakan dalam bekerja dengan regex .NET. Hal ini berisi bagian-bagian berikut:

Mesin Regex

Mesin regex di .NET diwakili oleh kelas Regex. Mesin regex bertanggung jawab untuk mengurai dan mengkompilasi regex, dan untuk melakukan operasi yang cocok dengan pola regex dengan string input. Mesin adalah komponen pusat dalam model objek regex .NET.

Anda dapat menggunakan mesin regex dengan salah satu dari dua cara:

  • Dengan memanggil metode statis kelas Regex. Parameter metode mencakup string input dan pola regex. Mesin regex menyimpan regex yang digunakan dalam panggilan metode statis, jadi panggilan berulang ke metode regex statis yang menggunakan regex yang sama menawarkan performa yang relatif baik.

  • Dengan membuat Regex instans objek, dengan meneruskan regex ke konstruktor kelas. Dalam hal ini, Regex objek tidak dapat diubah (baca-saja) dan mewakili mesin regex yang digabungkan erat dengan regex tunggal. Karena regex yang digunakan oleh Regex instans tidak di-cache, Anda tidak boleh membuat Regex instans objek beberapa kali dengan regex yang sama.

Anda dapat memanggil metode kelasRegex untuk melakukan operasi berikut:

  • Tentukan apakah string cocok dengan pola regex.

  • Ekstrak satu kecocokan atau kecocokan pertama.

  • Ekstrak semua kecocokan.

  • Ganti substring yang cocok.

  • Memisahkan string tunggal menjadi array string.

Operasi ini dijelaskan dalam bagian berikut.

Mencocokkan Pola Regex

Metode Regex.IsMatch mengembalikan true jika string cocok dengan pola, atau false jika tidak. Metode IsMatch ini sering digunakan untuk memvalidasi input string. Misalnya, kode berikut memastikan bahwa string cocok dengan nomor jaminan sosial yang valid di Amerika Serikat.

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

Pola regex ^\d{3}-\d{2}-\d{4}$ ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
^ Cocokkan awal string input.
\d{3} Cocokkan tiga digit desimal.
- Cocokkan tanda hubung.
\d{2} Cocokkan dua digit desimal.
- Cocokkan tanda hubung.
\d{4} Cocokkan empat angka desimal.
$ Cocokkan akhir string input.

Mengekstraksi Satu Kecocokan atau Kecocokan Pertama.

Metode Regex.Match mengembalikan objek Match yang berisi informasi tentang substring pertama yang cocok dengan pola regex. Jika properti Match.Success mengembalikan true, menunjukkan bahwa kecocokan ditemukan, Anda dapat mengambil informasi tentang kecocokan berikutnya dengan memanggil metode Match.NextMatch. Panggilan metode ini dapat dilanjutkan hingga properti Match.Success menghasilkan false. Misalnya, kode berikut menggunakan metode Regex.Match(String, String) untuk menemukan kemunculan pertama kata duplikat dalam string. Kemudian memanggil metode Match.NextMatch untuk menemukan kemunculan tambahan. Contoh memeriksa properti Match.Success setelah setiap panggilan metode untuk menentukan apakah kecocokan saat ini berhasil dan apakah panggilan ke metode Match.NextMatch harus diikuti.

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.

Pola regex \b(\w+)\W+(\1)\b ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\b Mulai kecocokan pada batas kata.
(\w+) Mencocokkan satu atau beberapa karakter kata. Ini adalah grup penangkapan pertama.
\W+ Cocokkan satu atau beberapa karakter non-kata.
(\1) Cocok dengan string pertama yang diambil. Ini adalah grup pengambilan kedua.
\b Akhiri pencocokan pada batas kata.

Mengekstrak Semua Kecocokan

Metode Regex.Matches mengembalikan objek MatchCollection yang berisi informasi tentang semua kecocokan yang ditemukan mesin regex dalam string input. Misalnya, contoh sebelumnya dapat ditulis ulang untuk memanggil metode Matches bukan metode Match dan NextMatch.

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.

Mengganti Substring yang Cocok

Metode menggantikan Regex.Replace setiap substring yang cocok dengan pola regex dengan string tertentu atau pola regex, dan mengembalikan seluruh string input dengan penggantian. Misalnya, kode berikut menambahkan simbol mata uang AS sebelum angka desimal dalam string.

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

Pola regex \b\d+\.\d{2}\b ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\b Memulai pencocokan dalam batas kata.
\d+ Cocokkan satu atau beberapa angka desimal.
\. Cocokkan tanda titik.
\d{2} Cocokkan dua digit desimal.
\b Mengakhiri pencocokan dalam batas kata.

Pola penggantian $$$& ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola String pengganti
$$ Karakter tanda dolar ($).
$& Seluruh substring yang cocok.

Memisahkan String Tunggal menjadi Array String

Metode Regex.Split ini membagi string input pada posisi yang ditentukan oleh kecocokan regex. Misalnya, kode berikut menempatkan item dalam daftar bernomor ke dalam array string.

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

Pola regex \b\d{1,2}\.\s ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\b Memulai pencocokan dalam batas kata.
\d{1,2} Cocokkan satu atau dua digit desimal.
\. Cocokkan tanda titik.
\s Cocokkan karakter spasi kosong.

MatchCollection dan Cocokkan objek

Metode regex mengembalikan dua objek yang merupakan bagian dari model objek regex: objek MatchCollection dan objek Match.

Kumpulan Kecocokan

Metode Regex.Matches mengembalikan objek MatchCollection yang berisi objek Match yang mewakili semua kecocokan yang ditemukan mesin regex, dalam urutan terjadinya dalam string input. Jika tidak ada kecocokan, metode mengembalikan objek MatchCollection tanpa anggota. Properti MatchCollection.Item[] memungkinkan Anda mengakses masing-masing anggota kumpulan menurut indeks, dari nol hingga satu kurang dari nilai properti MatchCollection.Count. Item[] adalah pengindeks kumpulan (dalam C#) dan properti default (dalam Visual Basic).

Secara default, panggilan ke metode Regex.Matches menggunakan evaluasi malas untuk mengisi objek MatchCollection. Akses ke properti yang memerlukan kumpulan yang terisi penuh, seperti properti MatchCollection.Count dan MatchCollection.Item[], mungkin melibatkan penalti performa. Karena itu, kami sarankan Anda mengakses kumpulan dengan menggunakan objek IEnumerator yang dikembalikan oleh metode MatchCollection.GetEnumerator. Bahasa individu menyediakan konstruksi, seperti For Each dalam Visual Basic dan foreach di C#, yang membungkus antarmuka kumpulan IEnumerator.

Contoh berikut menggunakan Regex.Matches(String) metode untuk mengisi objek MatchCollection dengan semua kecocokan yang ditemukan dalam string input. Contoh menghitung kumpulan, menyalin kecocokan ke array string, dan merekam posisi karakter dalam array bilangan bulat.

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.

Kecocokan

Kelas Match mewakili hasil dari satu kecocokan regex. Anda dapat mengakses objek Match dengan dua cara:

  • Dengan mengambilnya dari objek MatchCollection yang dikembalikan oleh metode Regex.Matches . Untuk mengambil objek individualMatch, iterasi kumpulan dengan menggunakan foreach konstruksi (dalam C#) atau For Each...Next (dalam Visual Basic), atau gunakan MatchCollection.Item[] properti untuk mengambil objek tertentu Match baik berdasarkan indeks atau berdasarkan nama. Anda juga dapat mengambil objek individual Match dari kumpulan dengan mengurutkan kumpulan menurut indeks, dari nol hingga satu lebih sedikit jumlah objek dalam kumpulan. Namun, metode ini tidak memanfaatkan evaluasi malas, karena mengakses properti MatchCollection.Count.

    Contoh berikut mengambil objek individual Match dari MatchCollection objek dengan melakukan iterasi kumpulan menggunakan foreach konstruksi atau For Each...Next. Ekspresi reguler hanya cocok dengan string "abc" dalam string input.

    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.
    
  • Dengan memanggil metode Regex.Match, yang mengembalikan objek Match yang mewakili kecocokan pertama dalam string atau bagian dari string. Anda dapat menentukan apakah kecocokan telah ditemukan dengan mengambil nilai properti Match.Success. Untuk mengambil Match objek yang mewakili kecocokan berikutnya, panggil Match.NextMatch metode berulang kali, hingga Success properti objek yang dikembalikan Match adalah false.

    Contoh berikut menggunakan metode Regex.Match(String, String) dan Match.NextMatch untuk mencocokkan string "abc" dalam string input.

    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.
    

Dua properti kelas Match menghasilkan objek kumpulan:

  • Properti Match.Groups mengembalikan GroupCollection objek yang berisi informasi tentang substring yang cocok dengan pengambilan grup dalam pola regex.

  • Properti Match.Captures mengembalikan CaptureCollection objek yang penggunaannya terbatas. Kumpulan tidak diisi untuk Match objek yang propertinya Success adalah false. Jika tidak, ini berisi satu objek Captureyang memiliki informasi yang sama dengan objek Match.

Untuk informasi selengkapnya tentang objek ini, lihat Bagian Kumpulan Grup dan Kumpulan Pengambilan nanti dalam topik ini.

Dua properti tambahan kelas Match memberikan informasi tentang kecocokan. Properti Match.Value mengembalikan substring dalam string input yang cocok dengan pola regex. Properti Match.Index mengembalikan posisi awal berbasis nol dari string yang cocok dalam string input.

Kelas ini Match juga memiliki dua metode pencocokan pola:

  • Metode Match.NextMatch menemukan kecocokan setelah kecocokan yang diwakili oleh objek saat ini Match , dan mengembalikan Match objek yang mewakili kecocokan tersebut.

  • Metode Match.Result melakukan operasi penggantian tertentu pada string yang cocok dan mengembalikan hasilnya.

Contoh berikut menggunakan Match.Result metode untuk menambahkan simbol $ dan spasi sebelum setiap angka yang menyertakan dua digit pecahan.

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

Pola regex \b\d+(,\d{3})*\.\d{2}\b didefinisikan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\b Memulai pencocokan dalam batas kata.
\d+ Cocokkan satu atau beberapa angka desimal.
(,\d{3})* Cocokkan nol atau lebih kemunculan koma diikuti oleh tiga digit desimal.
\. Cocokkan karakter titik desimal.
\d{2} Cocokkan dua digit desimal.
\b Mengakhiri pencocokan dalam batas kata.

Pola penggantian $$ $& menunjukkan bahwa substring yang cocok harus diganti dengan simbol tanda dolar ($) ( $$ pola), spasi, dan nilai kecocokan ( $& pola).

Kembali ke atas

Kumpulan Grup

Properti Match.Groups mengembalikan GroupCollection objek yang berisi Group objek yang mewakili grup yang diambil dalam satu kecocokan. Objek Group pertama dalam kumpulan (pada indeks nol) mewakili seluruh kecocokan. Setiap objek berikut mewakili hasil dari satu grup pengambilan.

Anda dapat mengambil objek individual Group dalam kumpulan dengan menggunakan properti GroupCollection.Item[]. Anda dapat mengambil grup yang tidak disebutkan namanya berdasarkan posisi ordinalnya dalam kumpulan, dan mengambil grup dengan nama baik berdasarkan nama atau berdasarkan posisi ordinal. Pengambilan yang tidak disebutkan namanya muncul terlebih dahulu dalam kumpulan, dan diindeks dari kiri ke kanan dalam urutan muncul dalam pola regex. Pengambilan dengan nama diindeks setelah pengambilan tanpa nama, dari kiri ke kanan dalam urutan muncul dalam pola regex. Untuk menentukan grup bernomor apa yang tersedia dalam kumpulan yang dikembalikan untuk metode pencocokan regex tertentu, Anda dapat memanggil metode instans Regex.GetGroupNumbers. Untuk menentukan grup dengan nama apa yang tersedia dalam kumpulan, Anda dapat memanggil metode instans Regex.GetGroupNames. Kedua metode ini sangat berguna dalam rutinitas tujuan umum yang menganalisis kecocokan yang ditemukan oleh regex apa pun.

Properti GroupCollection.Item[] adalah pengindeks kumpulan di C# dan properti default objek kumpulan di Visual Basic. Ini berarti bahwa objek individual Group dapat diakses oleh indeks (atau berdasarkan nama, dalam penentuan huruf grup dengan nama) sebagai berikut:

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

Contoh berikut mendefinisikan regex yang menggunakan konstruksi pengelompokan untuk mengambil bulan, hari, dan tahun dalam tanggal.

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

Pola regex \b(\w+)\s(\d{1,2}),\s(\d{4})\b didefinisikan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\b Memulai pencocokan dalam batas kata.
(\w+) Mencocokkan satu atau beberapa karakter kata. Ini adalah grup penangkapan pertama.
\s Cocokkan karakter spasi kosong.
(\d{1,2}) Cocokkan satu atau dua digit desimal. Ini adalah grup pengambilan kedua.
, Mencocokkan koma.
\s Cocokkan karakter spasi kosong.
(\d{4}) Cocokkan empat angka desimal. Ini adalah grup pengambilan ketiga.
\b Akhiri pencocokan pada batas kata.

Kembali ke atas

Grup yang Diambil

Kelas Group mewakili hasil dari satu grup pengambilan. Objek grup yang mewakili grup pengambilan yang ditentukan dalam regex dikembalikan oleh properti Item[] objek GroupCollection yang dikembalikan oleh properti Match.Groups. Properti Item[] adalah pengindeks (dalam C#) dan properti default (dalam Visual Basic) kelas Group. Anda juga dapat mengambil masing-masing anggota dengan mengurutkan kumpulan menggunakan konstruksi foreach atau For Each. Sebagai contoh, lihat bagian sebelumnya.

Contoh berikut menggunakan konstruksi pengelompokan berlapis untuk mengambil substring ke dalam grup. Pola regex (a(b))c yang cocok dengan string "abc". Ini menetapkan substring "ab" ke grup pengambilan pertama, dan substring "b" ke grup pengambilan kedua.

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

Contoh berikut menggunakan konstruksi pengelompokan dengan nama untuk mengambil substring dari string yang berisi data dalam format "DATANAME:VALUE", yang dipisahkan regex di titik dua (:).

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

Pola regex ^(?<name>\w+):(?<value>\w+) didefinisikan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
^ Mulai pencocokan di awal string input.
(?<name>\w+) Mencocokkan satu atau beberapa karakter kata. Nama grup pengambilan ini adalah name.
: Cocokkan titik dua.
(?<value>\w+) Mencocokkan satu atau beberapa karakter kata. Nama grup pengambilan ini adalah value.

Properti Group kelas memberikan informasi tentang grup yang diambil: Group.Value Properti berisi substring yang diambil, Group.Index properti menunjukkan posisi awal grup yang diambil dalam teks input, Group.Length properti berisi panjang teks yang diambil, dan Group.Success properti menunjukkan apakah substring cocok dengan pola yang ditentukan oleh grup pengambilan.

Menerapkan kuantifier ke grup (untuk informasi selengkapnya, lihat Kuantifier) memodifikasi hubungan satu pengambilan per grup pengambilan dengan dua cara:

  • Jika kuantifier * atau *? (yang menentukan nol atau lebih kecocokan) diterapkan ke grup, grup pengambilan mungkin tidak memiliki kecocokan dalam string input. Saat tidak ada teks yang diambil, properti objek Group diatur seperti yang diperlihatkan dalam tabel berikut.

    Properti grup Nilai
    Success false
    Value String.Empty
    Length 0

    Contoh berikut memberikan ilustrasi. Dalam pola regex aaa(bbb)*ccc, grup pengambilan pertama (substring "bbb") tidak dapat dicocokkan atau dicocokkan beberapa kali. Karena string input "aaaccc" cocok dengan pola, grup pengambilan tidak memiliki kecocokan.

    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.
    
  • Pengukur dapat mencocokkan beberapa kemunculan pola yang ditentukan oleh grup pengambilan. Dalam hal ini, Value properti dan Length objek Group hanya berisi informasi tentang substring terakhir yang diambil. Misalnya, regex berikut cocok dengan satu kalimat yang berakhiran titik. Ini menggunakan dua konstruksi pengelompokan: Yang pertama mengambil kata-kata individu bersama dengan karakter spasi putih; yang kedua mengambil kata-kata individual. Seperti yang ditunjukkan oleh output dari contoh, meski regex berhasil mengambil seluruh kalimat, grup pengambilan kedua hanya mengambil kata terakhir.

    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
    

Kembali ke atas

Kumpulan Pengambilan

Objek Group hanya berisi informasi tentang pengambilan terakhir. Namun, seluruh set pengambilan yang dibuat oleh grup pengambilan masih tersedia dari objek CaptureCollection yang dikembalikan oleh properti Group.Captures. Setiap anggota kumpulan adalah Capture objek yang mewakili pengambilan yang dibuat oleh grup pengambilan tersebut, dalam urutan pengambilannya (dan, oleh karena itu, dalam urutan string yang diambil dicocokkan dari kiri ke kanan dalam string input). Anda dapat mengambil objek individual Capture dari kumpulan dengan salah satu dari dua cara:

  • Dengan melakukan iterasi melalui kumpulan menggunakan konstruksi seperti foreach (dalam C#) atau For Each (dalam Visual Basic).

  • Dengan menggunakan CaptureCollection.Item[] properti untuk mengambil objek tertentu menurut indeks. Properti Item[] adalah CaptureCollection properti default objek (dalam Visual Basic) atau pengindeks (dalam C#).

Jika kuantifier tidak diterapkan ke grup pengambilan, objek CaptureCollection berisi satu objek Capture yang sedikit menarik, karena memberikan informasi tentang kecocokan yang sama dengan objeknya Group. Jika kuantifier diterapkan ke grup pengambilan, objek CaptureCollection berisi semua pengambilan yang dibuat oleh grup pengambilan, dan anggota terakhir kumpulan mewakili pengambilan yang sama dengan objek Group.

Misalnya, jika Anda menggunakan pola ((a(b))c)+ regex (di mana + kuantifier menentukan satu atau beberapa kecocokan) untuk menangkap kecocokan dari string "abcabcabc", objek CaptureCollection untuk setiap objek Group berisi tiga anggota.

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

Contoh berikut menggunakan ekspresi (Abc)+ reguler untuk menemukan satu atau beberapa eksekusi berturut-turut dari string "Abc" dalam string "XYZAbcAbcAbcXYZAbcAb". Contoh ini mengilustrasikan penggunaan properti Group.Captures untuk mengembalikan beberapa grup substring yang diambil.

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  

Kembali ke atas

Pengambilan Individual

Kelas Capture berisi hasil dari satu pengambilan subekspresi. Properti Capture.Value berisi teks yang cocok, dan properti Capture.Index menunjukkan posisi berbasis nol dalam string input tempat substring yang cocok dimulai.

Contoh berikut menguraikan string input untuk suhu kota yang dipilih. Koma (",") digunakan untuk memisahkan kota dan suhunya, dan titik koma (";") digunakan untuk memisahkan data setiap kota. Seluruh string input mewakili satu kecocokan. Dalam pola regex ((\w+(\s\w+)*),(\d+);)+, yang digunakan untuk mengurai string, nama kota ditetapkan ke grup pengambilan kedua, dan suhu ditetapkan ke grup pengambilan keempat.

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

Regex didefinisikan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\w+ Mencocokkan satu atau beberapa karakter kata.
(\s\w+)* Cocokkan nol atau lebih kemunculan karakter spasi diikuti oleh satu atau beberapa karakter kata. Pola ini cocok dengan nama kota multi-kata. Ini adalah grup pengambilan ketiga.
(\w+(\s\w+)*) Cocokkan satu atau beberapa karakter kata diikuti dengan nol atau lebih kemunculan karakter spasi putih dan satu atau beberapa karakter kata. Ini adalah grup pengambilan kedua.
, Mencocokkan koma.
(\d+) Cocokkan satu atau beberapa digit. Ini adalah grup penangkapan keempat.
; Cocokkan titik koma.
((\w+(\s\w+)*),(\d+);)+ Cocokkan pola kata diikuti dengan kata tambahan yang diikuti dengan koma, satu atau beberapa digit, dan titik koma, satu atau beberapa kali. Ini adalah grup penangkapan pertama.

Lihat juga