Bagikan melalui


Jangkar dalam Regex

Jangkar, atau pernyataan atom dengan lebar nol, menentukan posisi dalam string tempat kecocokan harus terjadi. Saat Anda menggunakan jangkar dalam ekspresi pencarian Anda, mesin regex tidak memproses melalui string atau mengonsumsi karakter; ia hanya mencari kecocokan di posisi yang telah ditentukan. Misalnya, ^ menentukan bahwa kecocokan harus dimulai di awal baris atau string. Maka regex ^http: mencocokkan "http:" hanya ketika itu terjadi di awal baris. Tabel berikut mencantumkan jangkar yang didukung oleh regex di .NET.

Jangkar Deskripsi
^ Secara default, kecocokan harus terjadi di awal string; dalam mode beberapa baris, kecocokan harus terjadi di awal baris. Untuk informasi selengkapnya, lihat Awal String atau Baris.
$ Secara default, kecocokan harus terjadi di akhir string atau sebelum \n di akhir string; dalam mode beberapa baris, kecocokan harus terjadi sebelum akhir baris atau sebelum \n di akhir baris. Untuk informasi selengkapnya, lihat Akhir String atau Baris.
\A Kecocokan harus terjadi di awal string saja (tidak ada dukungan untuk beberapa baris). Untuk informasi selengkapnya, lihat Awal String Saja.
\Z Kecocokan harus terjadi di akhir string atau sebelum \n di akhir string. Untuk informasi selengkapnya, lihat Akhir String atau Sebelum Mengakhiri Baris Baru.
\z Kecocokan harus terjadi di akhir string saja. Untuk informasi selengkapnya, lihat Akhir String Saja.
\G Kecocokan harus dimulai pada posisi tempat kecocokan sebelumnya berakhir, atau jika tidak ada kecocokan sebelumnya, pada posisi di string tempat pencocokan dimulai. Untuk informasi selengkapnya, lihat Kecocokan yang Berdekatan.
\b Kecocokan harus terjadi pada batas kata. Untuk informasi selengkapnya, lihat Batas Kata.
\B Kecocokan tidak boleh terjadi pada batas kata. Untuk informasi selengkapnya, lihat Batas Non-Kata.

Awal String atau Baris: ^

Secara default, jangkar ^ menentukan bahwa pola berikut harus dimulai pada posisi karakter pertama dari string. Jika Anda menggunakan ^ dengan opsi RegexOptions.Multiline (lihat Opsi Regex), kecocokan harus terjadi di awal setiap baris.

Contoh berikut menggunakan jangkar ^ dalam regex yang mengekstrak informasi tentang tahun-tahun saat beberapa tim bisbol profesional ada. Contoh tersebut memanggil dua kelebihan beban dari metode Regex.Matches:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957\n" +
                     "Chicago Cubs, National League, 1903-present\n" +
                     "Detroit Tigers, American League, 1901-present\n" +
                     "New York Giants, National League, 1885-1957\n" +
                     "Washington Senators, American League, 1901-1960\n";
        string pattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+";
        Match match;

        match = Regex.Match(input, pattern);
        while (match.Success)
        {
            Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
                Console.Write(capture.Value);

            Console.WriteLine(".");
            match = match.NextMatch();
        }
        Console.WriteLine();

        match = Regex.Match(input, pattern, RegexOptions.Multiline);
        while (match.Success)
        {
            Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
                Console.Write(capture.Value);

            Console.WriteLine(".");
            match = match.NextMatch();
        }
        Console.WriteLine();
    }
}
// The example displays the following output:
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    The Chicago Cubs played in the National League in 1903-present.
//    The Detroit Tigers played in the American League in 1901-present.
//    The New York Giants played in the National League in 1885-1957.
//    The Washington Senators played in the American League in 1901-1960.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + vbCrLf +
                              "Chicago Cubs, National League, 1903-present" + vbCrLf +
                              "Detroit Tigers, American League, 1901-present" + vbCrLf +
                              "New York Giants, National League, 1885-1957" + vbCrLf +
                              "Washington Senators, American League, 1901-1960" + vbCrLf

        Dim pattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"
        Dim match As Match

        match = Regex.Match(input, pattern)
        Do While match.Success
            Console.Write("The {0} played in the {1} in",
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
                Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            match = match.NextMatch()
        Loop
        Console.WriteLine()

        match = Regex.Match(input, pattern, RegexOptions.Multiline)
        Do While match.Success
            Console.Write("The {0} played in the {1} in",
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
                Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            match = match.NextMatch()
        Loop
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    The Chicago Cubs played in the National League in 1903-present.
'    The Detroit Tigers played in the American League in 1901-present.
'    The New York Giants played in the National League in 1885-1957.
'    The Washington Senators played in the American League in 1901-1960.

Pola regex ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+ didefinisikan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
^ Memulai pencocokan di awal string input (atau awal baris jika metode dipanggil menggunakan opsi RegexOptions.Multiline).
((\w+(\s?)){2,} Mencocokkan satu atau beberapa karakter kata yang diikuti dengan nol atau dengan satu spasi setidaknya dua kali. Ini adalah grup penangkapan pertama. Ekspresi ini juga mendefinisikan kelompok penangkap kedua dan ketiga: Yang kedua terdiri dari kata yang ditangkap, dan yang ketiga terdiri dari spasi kosong yang ditangkap.
,\s Mencocokkan koma yang diikuti oleh karakter spasi kosong.
(\w+\s\w+) Mencocokkan satu atau beberapa karakter kata yang diikuti oleh spasi, diikuti oleh satu atau lebih karakter kata. Ini adalah grup penangkapan keempat.
, Mencocokkan koma.
\s\d{4} Mencocokkan spasi yang diikuti dengan empat digit desimal.
(-(\d{4}|present))? Mencocokkan nol atau satu kemunculan dari tanda hubung yang diikuti oleh empat digit desimal atau string "present". Ini adalah grup penangkapan keenam. Ia juga menyertakan grup penangkapan ketujuh.
,? Mencocokkan nol atau satu kemunculan dari koma.
(\s\d{4}(-(\d{4}|present))?,?)+ Mencocokkan satu atau beberapa kemunculan berikut: spasi, empat digit desimal, nol atau satu kemunculan tanda hubung yang diikuti oleh empat digit desimal atau string "present", dan nol atau satu koma. Ini adalah grup penangkapan kelima.

Akhir String atau Baris: $

Jangkar $ menentukan bahwa pola sebelumnya harus terjadi di akhir string input, atau sebelum \n di akhir string input.

Jika Anda menggunakan $ dengan opsi RegexOptions.Multiline, pencocokan juga dapat terjadi di akhir baris. Perhatikan bahwa $ terpenuhi pada \n tetapi tidak pada \r\n (kombinasi pengembalian pengangkutan dan karakter baris baru, atau CR/LF). Untuk menangani kombinasi karakter CR/LF, sertakan \r?$ dalam pola ekspresi reguler. Perhatikan bahwa \r?$ akan menyertakan apa pun \r dalam kecocokan.

Contoh berikut menambahkan jangkar $ ke pola regex yang digunakan dalam contoh di bagian Awal String atau Baris. Saat digunakan dengan string input asli, yang mencakup lima baris teks, metode Regex.Matches(String, String) tidak dapat menemukan kecocokan, karena akhir baris pertama tidak cocok dengan pola $. Ketika string input asli dibagi menjadi array string, metode Regex.Matches(String, String) berhasil mencocokkan masing-masing dari lima baris. Regex.Matches(String, String, RegexOptions) Ketika metode dipanggil dengan parameter diatur options ke , tidak ada kecocokan RegexOptions.Multilineyang ditemukan karena pola ekspresi reguler tidak memperhitungkan karakter \rpengembalian pengangkutan . Namun, ketika pola regex dimodifikasi dengan mengganti $ dengan \r?$, memanggil kembali metode Regex.Matches(String, String, RegexOptions) dengan parameter options yang diatur ke RegexOptions.Multiline menemukan lima kecocokan.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string cr = Environment.NewLine;
        string input = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + cr +
                       "Chicago Cubs, National League, 1903-present" + cr +
                       "Detroit Tigers, American League, 1901-present" + cr +
                       "New York Giants, National League, 1885-1957" + cr +
                       "Washington Senators, American League, 1901-1960" + cr;
        Match match;

        string basePattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+";
        string pattern = basePattern + "$";
        Console.WriteLine("Attempting to match the entire input string:");
        match = Regex.Match(input, pattern);
        while (match.Success)
        {
            Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
                Console.Write(capture.Value);

            Console.WriteLine(".");
            match = match.NextMatch();
        }
        Console.WriteLine();

        string[] teams = input.Split(new String[] { cr }, StringSplitOptions.RemoveEmptyEntries);
        Console.WriteLine("Attempting to match each element in a string array:");
        foreach (string team in teams)
        {
            match = Regex.Match(team, pattern);
            if (match.Success)
            {
                Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
                foreach (Capture capture in match.Groups[5].Captures)
                    Console.Write(capture.Value);
                Console.WriteLine(".");
            }
        }
        Console.WriteLine();

        Console.WriteLine("Attempting to match each line of an input string with '$':");
        match = Regex.Match(input, pattern, RegexOptions.Multiline);
        while (match.Success)
        {
            Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
                Console.Write(capture.Value);

            Console.WriteLine(".");
            match = match.NextMatch();
        }
        Console.WriteLine();

        pattern = basePattern + "\r?$";
        Console.WriteLine(@"Attempting to match each line of an input string with '\r?$':");
        match = Regex.Match(input, pattern, RegexOptions.Multiline);
        while (match.Success)
        {
            Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
                Console.Write(capture.Value);

            Console.WriteLine(".");
            match = match.NextMatch();
        }
        Console.WriteLine();
    }
}
// The example displays the following output:
//    Attempting to match the entire input string:
//
//    Attempting to match each element in a string array:
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    The Chicago Cubs played in the National League in 1903-present.
//    The Detroit Tigers played in the American League in 1901-present.
//    The New York Giants played in the National League in 1885-1957.
//    The Washington Senators played in the American League in 1901-1960.
//
//    Attempting to match each line of an input string with '$':
//
//    Attempting to match each line of an input string with '\r?$':
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
//    The Chicago Cubs played in the National League in 1903-present.
//    The Detroit Tigers played in the American League in 1901-present.
//    The New York Giants played in the National League in 1885-1957.
//    The Washington Senators played in the American League in 1901-1960.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + vbCrLf +
                              "Chicago Cubs, National League, 1903-present" + vbCrLf +
                              "Detroit Tigers, American League, 1901-present" + vbCrLf +
                              "New York Giants, National League, 1885-1957" + vbCrLf +
                              "Washington Senators, American League, 1901-1960" + vbCrLf

        Dim basePattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"
        Dim match As Match

        Dim pattern As String = basePattern + "$"
        Console.WriteLine("Attempting to match the entire input string:")
        match = Regex.Match(input, pattern)
        Do While match.Success
            Console.Write("The {0} played in the {1} in",
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
                Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            match = match.NextMatch()
        Loop
        Console.WriteLine()

        Dim teams() As String = input.Split(New String() {vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
        Console.WriteLine("Attempting to match each element in a string array:")
        For Each team As String In teams
            match = Regex.Match(team, pattern)
            If match.Success Then
                Console.Write("The {0} played in the {1} in",
                               match.Groups(1).Value, match.Groups(4).Value)
                For Each capture As Capture In match.Groups(5).Captures
                    Console.Write(capture.Value)
                Next
                Console.WriteLine(".")
            End If
        Next
        Console.WriteLine()

        Console.WriteLine("Attempting to match each line of an input string with '$':")
        match = Regex.Match(input, pattern, RegexOptions.Multiline)
        Do While match.Success
            Console.Write("The {0} played in the {1} in",
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
                Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            match = match.NextMatch()
        Loop
        Console.WriteLine()

        pattern = basePattern + "\r?$"
        Console.WriteLine("Attempting to match each line of an input string with '\r?$':")
        match = Regex.Match(input, pattern, RegexOptions.Multiline)
        Do While match.Success
            Console.Write("The {0} played in the {1} in",
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
                Console.Write(capture.Value)
            Next
            Console.WriteLine(".")

            match = match.NextMatch()
        Loop
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'    Attempting to match the entire input string:
'    
'    Attempting to match each element in a string array:
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    The Chicago Cubs played in the National League in 1903-present.
'    The Detroit Tigers played in the American League in 1901-present.
'    The New York Giants played in the National League in 1885-1957.
'    The Washington Senators played in the American League in 1901-1960.
'    
'    Attempting to match each line of an input string with '$':
'    
'    Attempting to match each line of an input string with '\r?$':
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
'    The Chicago Cubs played in the National League in 1903-present.
'    The Detroit Tigers played in the American League in 1901-present.
'    The New York Giants played in the National League in 1885-1957.
'    The Washington Senators played in the American League in 1901-1960.

Awal String Saja: \A

Jangkar \A menentukan bahwa pencocokan harus terjadi di awal string input. Ia identik dengan jangkar ^, namun \A mengabaikan opsi RegexOptions.Multiline. Oleh karena itu, ia hanya dapat mencocokkan awal baris pertama dalam string input beberapa baris.

Contoh berikut mirip dengan contoh untuk jangkar ^ dan $. Contoh berikut menggunakan jangkar \A dalam regex yang mengekstrak informasi tentang tahun-tahun saat beberapa tim bisbol profesional ada. String input mencakup lima baris. Panggilan ke kelebihan beban Regex.Matches(String, String, RegexOptions) hanya menemukan substring pertama dalam string input yang cocok dengan pola regex. Seperti yang ditunjukkan pada contoh, opsi Multiline tidak berpengaruh.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957\n" +
                       "Chicago Cubs, National League, 1903-present\n" +
                       "Detroit Tigers, American League, 1901-present\n" +
                       "New York Giants, National League, 1885-1957\n" +
                       "Washington Senators, American League, 1901-1960\n";

        string pattern = @"\A((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+";

        Match match = Regex.Match(input, pattern, RegexOptions.Multiline);
        while (match.Success)
        {
            Console.Write("The {0} played in the {1} in",
                              match.Groups[1].Value, match.Groups[4].Value);
            foreach (Capture capture in match.Groups[5].Captures)
                Console.Write(capture.Value);

            Console.WriteLine(".");
            match = match.NextMatch();
        }
        Console.WriteLine();
    }
}
// The example displays the following output:
//    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957" + vbCrLf +
                            "Chicago Cubs, National League, 1903-present" + vbCrLf +
                            "Detroit Tigers, American League, 1901-present" + vbCrLf +
                            "New York Giants, National League, 1885-1957" + vbCrLf +
                            "Washington Senators, American League, 1901-1960" + vbCrLf

        Dim pattern As String = "\A((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"

        Dim match As Match = Regex.Match(input, pattern, RegexOptions.Multiline)
        Do While match.Success
            Console.Write("The {0} played in the {1} in",
                              match.Groups(1).Value, match.Groups(4).Value)
            For Each capture As Capture In match.Groups(5).Captures
                Console.Write(capture.Value)
            Next
            Console.WriteLine(".")
            match = match.NextMatch()
        Loop
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'    The Brooklyn Dodgers played in the National League in 1911, 1912, 1932-1957.

Akhir String atau Sebelum Mengakhiri Baris Baru: \Z

Jangkar \Z menentukan bahwa pencocokan harus terjadi di akhir string input, atau sebelum \n di akhir string input. Ia identik dengan jangkar $, namun \Z mengabaikan opsi RegexOptions.Multiline. Oleh karena itu, dalam string multibaris, string hanya dapat dipenuhi pada akhir baris terakhir, atau baris terakhir sebelum \n.

Perhatikan bahwa \Z puas pada \n tetapi tidak terpenuhi pada \r\n (kombinasi karakter CR/LF). Untuk memperlakukan CR/LF seolah-olah itu \n, sertakan \r?\Z dalam pola ekspresi reguler. Perhatikan bahwa ini akan membuat \r bagian dari pertandingan.

Contoh berikut menggunakan jangkar \Z dalam regex yang mirip dengan contoh di bagian Awal String atau Baris, yang mengekstrak informasi tentang tahun-tahun saat beberapa tim bisbol profesional ada. Subekspresi \r?\Z dalam ekspresi ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z reguler terpenuhi di akhir string, dan juga di akhir string yang berakhir dengan \n atau \r\n. Akibatnya, setiap elemen dalam array cocok dengan pola regex.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string[] inputs = { "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",
                          "Chicago Cubs, National League, 1903-present" + Environment.NewLine,
                          "Detroit Tigers, American League, 1901-present" + Regex.Unescape(@"\n"),
                          "New York Giants, National League, 1885-1957",
                          "Washington Senators, American League, 1901-1960" + Environment.NewLine};
        string pattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z";

        foreach (string input in inputs)
        {
            Console.WriteLine(Regex.Escape(input));
            Match match = Regex.Match(input, pattern);
            if (match.Success)
                Console.WriteLine("   Match succeeded.");
            else
                Console.WriteLine("   Match failed.");
        }
    }
}
// The example displays the following output:
//    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
//       Match succeeded.
//    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
//       Match succeeded.
//    Detroit\ Tigers,\ American\ League,\ 1901-present\n
//       Match succeeded.
//    New\ York\ Giants,\ National\ League,\ 1885-1957
//       Match succeeded.
//    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
//       Match succeeded.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim inputs() As String = {"Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",
                              "Chicago Cubs, National League, 1903-present" + vbCrLf,
                              "Detroit Tigers, American League, 1901-present" + vbLf,
                              "New York Giants, National League, 1885-1957",
                              "Washington Senators, American League, 1901-1960" + vbCrLf}
        Dim pattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z"

        For Each input As String In inputs
            Console.WriteLine(Regex.Escape(input))
            Dim match As Match = Regex.Match(input, pattern)
            If match.Success Then
                Console.WriteLine("   Match succeeded.")
            Else
                Console.WriteLine("   Match failed.")
            End If
        Next
    End Sub
End Module
' The example displays the following output:
'    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
'       Match succeeded.
'    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
'       Match succeeded.
'    Detroit\ Tigers,\ American\ League,\ 1901-present\n
'       Match succeeded.
'    New\ York\ Giants,\ National\ League,\ 1885-1957
'       Match succeeded.
'    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
'       Match succeeded.

Akhir String Saja: \z

Jangkar \z menentukan bahwa pencocokan harus terjadi di akhir string input. Seperti elemen bahasa $, \z mengabaikan opsi RegexOptions.Multiline. \Z Tidak seperti elemen bahasa, \z tidak puas dengan \n karakter di akhir string. Oleh karena itu, itu hanya dapat mencocokkan akhir string input.

Contoh berikut menggunakan jangkar \z dalam regex yang tidak mirip dengan contoh di bagian sebelumnya, yang mengekstrak informasi tentang tahun-tahun saat beberapa tim bisbol profesional ada. Contoh tersebut mencoba mencocokkan masing-masing dari lima elemen dalam array string dengan pola regex ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z. Dua string berakhir dengan karakter umpan baris atau pengembalian pengangkutan, satu string berakhir dengan karakter umpan baris, dan dua string berakhir tanpa karakter umpan baris atau pengembalian pengangkutan. Seperti yang ditunjukkan output, hanya string tanpa umpan baris atau pengembalian pengangkutan yang cocok dengan pola.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string[] inputs = { "Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",
                          "Chicago Cubs, National League, 1903-present" + Environment.NewLine,
                          "Detroit Tigers, American League, 1901-present\n",
                          "New York Giants, National League, 1885-1957",
                          "Washington Senators, American League, 1901-1960" + Environment.NewLine };
        string pattern = @"^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z";

        foreach (string input in inputs)
        {
            Console.WriteLine(Regex.Escape(input));
            Match match = Regex.Match(input, pattern);
            if (match.Success)
                Console.WriteLine("   Match succeeded.");
            else
                Console.WriteLine("   Match failed.");
        }
    }
}
// The example displays the following output:
//    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
//       Match succeeded.
//    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
//       Match failed.
//    Detroit\ Tigers,\ American\ League,\ 1901-present\n
//       Match failed.
//    New\ York\ Giants,\ National\ League,\ 1885-1957
//       Match succeeded.
//    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
//       Match failed.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim inputs() As String = {"Brooklyn Dodgers, National League, 1911, 1912, 1932-1957",
                              "Chicago Cubs, National League, 1903-present" + vbCrLf,
                              "Detroit Tigers, American League, 1901-present" + vbLf,
                              "New York Giants, National League, 1885-1957",
                              "Washington Senators, American League, 1901-1960" + vbCrLf}
        Dim pattern As String = "^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\z"

        For Each input As String In inputs
            Console.WriteLine(Regex.Escape(input))
            Dim match As Match = Regex.Match(input, pattern)
            If match.Success Then
                Console.WriteLine("   Match succeeded.")
            Else
                Console.WriteLine("   Match failed.")
            End If
        Next
    End Sub
End Module
' The example displays the following output:
'    Brooklyn\ Dodgers,\ National\ League,\ 1911,\ 1912,\ 1932-1957
'       Match succeeded.
'    Chicago\ Cubs,\ National\ League,\ 1903-present\r\n
'       Match failed.
'    Detroit\ Tigers,\ American\ League,\ 1901-present\n
'       Match failed.
'    New\ York\ Giants,\ National\ League,\ 1885-1957
'       Match succeeded.
'    Washington\ Senators,\ American\ League,\ 1901-1960\r\n
'       Match failed.

Kecocokan yang Berdekatan: \G

Jangkar \G menetapkan bahwa kecocokan harus terjadi pada titik tempat kecocokan sebelumnya berakhir, atau jika tidak ada kecocokan sebelumnya, pada posisi di string tempat pencocokan dimulai. Ketika Anda menggunakan jangkar ini dengan metode Regex.Matches atau Match.NextMatch, ia memastikan bahwa semua kecocokan berdekatan.

Tip

Biasanya, Anda menempatkan \G jangkar di ujung kiri pola Anda. Dalam kasus yang jarang Anda melakukan pencarian kanan-ke-kiri, letakkan \G jangkar di ujung kanan pola Anda.

Contoh berikut menggunakan regex untuk mengekstrak nama-nama spesies hewan pengerat dari string yang dibatasi koma.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "capybara,squirrel,chipmunk,porcupine,gopher," +
                       "beaver,groundhog,hamster,guinea pig,gerbil," +
                       "chinchilla,prairie dog,mouse,rat";
        string pattern = @"\G(\w+\s?\w*),?";
        Match match = Regex.Match(input, pattern);
        while (match.Success)
        {
            Console.WriteLine(match.Groups[1].Value);
            match = match.NextMatch();
        }
    }
}
// The example displays the following output:
//       capybara
//       squirrel
//       chipmunk
//       porcupine
//       gopher
//       beaver
//       groundhog
//       hamster
//       guinea pig
//       gerbil
//       chinchilla
//       prairie dog
//       mouse
//       rat
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "capybara,squirrel,chipmunk,porcupine,gopher," +
                              "beaver,groundhog,hamster,guinea pig,gerbil," +
                              "chinchilla,prairie dog,mouse,rat"
        Dim pattern As String = "\G(\w+\s?\w*),?"
        Dim match As Match = Regex.Match(input, pattern)
        Do While match.Success
            Console.WriteLine(match.Groups(1).Value)
            match = match.NextMatch()
        Loop
    End Sub
End Module
' The example displays the following output:
'       capybara
'       squirrel
'       chipmunk
'       porcupine
'       gopher
'       beaver
'       groundhog
'       hamster
'       guinea pig
'       gerbil
'       chinchilla
'       prairie dog
'       mouse
'       rat

Regex \G(\w+\s?\w*),? ditafsirkan seperti yang diperlihatkan dalam tabel berikut.

Pola Deskripsi
\G Memulai di tempat pencocokan terakhir berakhir.
\w+ Mencocokkan satu atau beberapa karakter kata.
\s? Mencocokkan nol atau satu spasi.
\w* Mencocokkan nol atau beberapa karakter kata.
(\w+\s?\w*) Mencocokkan satu atau beberapa karakter kata yang diikuti dengan nol atau satu spasi, yang diikuti dengan nol atau beberapa karakter kata. Ini adalah grup penangkapan pertama.
,? Mencocokkan nol atau satu kemunculan dari karakter koma harfiah.

Batas Kata: \b

Jangkar \b menentukan bahwa pencocokan harus terjadi pada batas antara karakter kata (elemen bahasa \w) dan karakter non-kata (elemen bahasa \W). Karakter kata terdiri dari karakter alfanumerik dan garis bawah; Karakter non-kata adalah karakter apa pun yang bukan alfanumerik atau garis bawah. (Untuk informasi selengkapnya, lihat Kelas Karakter.) Kecocokan juga dapat terjadi pada batas kata di awal atau akhir string.

Jangkar \b sering digunakan untuk memastikan bahwa subekspresi cocok dengan seluruh kata, bukan hanya awal atau akhir kata. Regex \bare\w*\b dalam contoh berikut mengilustrasikan penggunaan ini. Ia mencocokkan kata apa pun yang dimulai dengan substring "are". Output dari contoh juga menggambarkan bahwa \b mencocokkan awal dan akhir string input.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "area bare arena mare";
        string pattern = @"\bare\w*\b";
        Console.WriteLine("Words that begin with 'are':");
        foreach (Match match in Regex.Matches(input, pattern))
            Console.WriteLine("'{0}' found at position {1}",
                              match.Value, match.Index);
    }
}
// The example displays the following output:
//       Words that begin with 'are':
//       'area' found at position 0
//       'arena' found at position 10
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "area bare arena mare"
        Dim pattern As String = "\bare\w*\b"
        Console.WriteLine("Words that begin with 'are':")
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("'{0}' found at position {1}",
                              match.Value, match.Index)
        Next
    End Sub
End Module
' The example displays the following output:
'       Words that begin with 'are':
'       'area' found at position 0
'       'arena' found at position 10

Pola regex ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\b Memulai pencocokan dalam batas kata.
are Mencocokkan substring "are".
\w* Mencocokkan nol atau beberapa karakter kata.
\b Mengakhiri pencocokan dalam batas kata.

Batas Non-Kata: \B

Jangkar \B menentukan bahwa kecocokan tidak boleh terjadi pada batas kata. Ini adalah kebalikan dari jangkar \b.

Contoh berikut menggunakan jangkar \B untuk menemukan kemunculan substring "qu" dalam sebuah kata. Pola regex \Bqu\w+ mencocokkan substring yang dimulai dengan "qu" yang tidak memulai sebuah kata dan yang berlanjut ke akhir kata.

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "equity queen equip acquaint quiet";
        string pattern = @"\Bqu\w+";
        foreach (Match match in Regex.Matches(input, pattern))
            Console.WriteLine("'{0}' found at position {1}",
                              match.Value, match.Index);
    }
}
// The example displays the following output:
//       'quity' found at position 1
//       'quip' found at position 14
//       'quaint' found at position 21
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "equity queen equip acquaint quiet"
        Dim pattern As String = "\Bqu\w+"
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("'{0}' found at position {1}",
                              match.Value, match.Index)
        Next
    End Sub
End Module
' The example displays the following output:
'       'quity' found at position 1
'       'quip' found at position 14
'       'quaint' found at position 21

Pola regex ditafsirkan seperti yang ditunjukkan pada tabel berikut.

Pola Deskripsi
\B Tidak memulai pencocokan pada batas kata.
qu Mencocokkan substring "are".
\w+ Mencocokkan satu atau beberapa karakter kata.

Lihat juga