Kotvy v regulárních výrazech

Ukotvení nebo atomické kontrolní výrazy s nulovou šířkou určují pozici v řetězci, kde musí dojít ke shodě. Pokud ve vyhledávacím výrazu použijete ukotvení, modul regulárních výrazů neprojde řetězcem ani nespotřebovává znaky; hledá shodu pouze v zadané pozici. Určuje například, ^ že shoda musí začínat na začátku řádku nebo řetězce. Regulární výraz ^http: proto odpovídá "http:", pouze pokud se vyskytuje na začátku řádku. Následující tabulka uvádí ukotvení podporovaná regulárními výrazy v .NET.

Záložka Popis
^ Ve výchozím nastavení musí shoda nacházet na začátku řetězce; ve víceřádkovém režimu musí nacházet na začátku řádku. Další informace naleznete v tématu Začátek řetězce nebo řádku.
$ Ve výchozím nastavení musí shoda nacházet na konci řetězce nebo před \n koncem řetězce. Ve víceřádkovém režimu se musí nacházet na konci řádku nebo před \n koncem řádku. Další informace naleznete v tématu Konec řetězce nebo řádku.
\A Shoda musí nacházet pouze na začátku řetězce (bez podpory víceřádkového řetězce). Další informace naleznete v tématu Pouze začátek řetězce.
\Z Shoda se musí nacházet na konci řetězce nebo před \n koncem řetězce. Další informace naleznete v tématu Konec řetězce nebo Před ukončením nového řádku.
\z Shoda se musí nacházet pouze na konci řetězce. Další informace naleznete v tématu Pouze konec řetězce.
\G Shoda musí začínat na pozici, kde předchozí shoda skončila, nebo pokud nebyla žádná předchozí shoda, na pozici v řetězci, kde začalo párování. Další informace naleznete v tématu Souvislé shody.
\b Shoda musí nastat na hranici slova. Další informace naleznete v tématu Hranice aplikace Word.
\B Shoda nesmí nastat na hranici slova. Další informace naleznete v tématu Hranice jiného slova.

Na začátku řetězce nebo řádku: ^

Ve výchozím nastavení ukotvení určuje, ^ že následující vzor musí začínat na první pozici znaku řetězce. Pokud použijete ^ s RegexOptions.Multiline možností (viz Možnosti regulárního výrazu), musí shoda nacházet na začátku každého řádku.

Následující příklad používá ukotvení ^ v regulárním výrazu, který extrahuje informace o letech, během kterých existovaly některé profesionální baseballové týmy. Příklad volá dvě přetížení Regex.Matches metody:

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.

Vzor regulárního výrazu ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+ je definován, jak je znázorněno v následující tabulce.

Vzor Popis
^ Zahajte shodu na začátku vstupního řetězce (nebo na začátku řádku, pokud je volána metoda s RegexOptions.Multiline možností).
((\w+(\s?)){2,} Porovná jeden nebo více znaků slova následovaných nulou nebo jednou mezerou alespoň dvakrát. Toto je první zachytávající skupina. Tento výraz také definuje druhou a třetí skupinu zachycení: Druhá se skládá z zachyceného slova a třetí se skládá z zachyceného prázdného místa.
,\s Porovná čárku následovanou prázdným znakem.
(\w+\s\w+) Porovná jeden nebo více znaků slova následovaných mezerou a za ním jeden nebo více znaků slova. Toto je čtvrtá skupina zachycení.
, Porovná čárku.
\s\d{4} Porovná mezeru následovanou čtyřmi desetinnými číslicemi.
(-(\d{4}|present))? Porovná žádný nebo jeden výskyt spojovníku následovaného čtyřmi desetinnými číslicemi nebo řetězcem "present". Toto je šestá skupina zachycení. Zahrnuje také sedmou zachytávání skupiny.
,? Porovná žádný nebo jeden výskyt čárky.
(\s\d{4}(-(\d{4}|present))?,?)+ Porovná jeden nebo více výskytů následujícího: mezeru, čtyři desetinné číslice, nula nebo jeden výskyt spojovníku následovaného čtyřmi desetinnými číslicemi nebo řetězcem "present" a nula nebo jedna čárka. Toto je pátá skupina zachycení.

Na konci řetězce nebo řádku: $

Ukotvení $ určuje, že předchozí vzor musí nastat na konci vstupního řetězce nebo před \n koncem vstupního řetězce.

Pokud použijete $ s RegexOptions.Multiline možností, může se shoda objevit také na konci řádku. Všimněte si, že $ je splněna, \n ale ne v \r\n (kombinace znaků návratu na začátek řádku a nového řádku nebo CR/LF). Chcete-li zpracovat kombinaci znaků CR/LF, zahrňte \r?$ do vzoru regulárního výrazu. Všimněte si, že \r?$ do shody se zahrnou všechny \r .

Následující příklad přidá ukotvení $ do vzoru regulárního výrazu použitého v příkladu v části Začátek řetězce nebo řádku . Při použití s původním vstupním řetězcem, který obsahuje pět řádků textu, Regex.Matches(String, String) metoda nemůže najít shodu, protože konec prvního řádku neodpovídá $ vzoru. Pokud je původní vstupní řetězec rozdělen do pole řetězců, Regex.Matches(String, String) metoda úspěšně odpovídá každému z pěti řádků. Regex.Matches(String, String, RegexOptions) Při zavolání metody s options parametrem nastaveným na RegexOptions.Multiline, nejsou nalezeny žádné shody, protože vzor regulárního výrazu neodpovídá návratový znak \rřádku . Pokud je však vzor regulárního výrazu změněn nahrazením $\r?$metodu Regex.Matches(String, String, RegexOptions)options s parametrem nastaveným znovu RegexOptions.Multiline najde pět shod.

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.

Jen za začátku řetězce: \A

Ukotvení \A určuje, že shoda musí nacházet na začátku vstupního řetězce. Je identický s ukotvení^, s tím rozdílemRegexOptions.Multiline, že \A tuto možnost ignoruje. Proto může odpovídat pouze začátku prvního řádku ve vstupním řetězci s více řádky.

Následující příklad je podobný příkladům ^ pro ukotvení a $ ukotvení. Používá kotvu \A v regulárním výrazu, který extrahuje informace o letech, během kterých existovaly některé profesionální baseballové týmy. Vstupní řetězec obsahuje pět řádků. Volání Regex.Matches(String, String, RegexOptions) metody najde pouze první podřetězce ve vstupním řetězci, který odpovídá vzoru regulárního výrazu. Jak ukazuje příklad, Multiline možnost nemá žádný vliv.

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.

Na konci řetězce nebo před novým řádkem na konci řetězce: \Z

Ukotvení \Z určuje, že shoda musí nacházet na konci vstupního řetězce nebo před \n koncem vstupního řetězce. Je identický s ukotvení$, s tím rozdílemRegexOptions.Multiline, že \Z tuto možnost ignoruje. Proto může být ve víceřádkovém řetězci splněn pouze na konci posledního řádku nebo posledním řádkem před \n.

Všimněte si, že \Z je splněna \n , ale není splněna v \r\n (kombinace znaků CR/LF). Pokud chcete zacházet s CR/LF, jako by tomu bylo \n, zahrňte \r?\Z do vzoru regulárního výrazu. Všimněte si, že se tím stane \r část shody.

Následující příklad používá ukotvení \Z v regulárním výrazu, který je podobný příkladu v části Začátek řetězce nebo řádku , který extrahuje informace o letech, během kterých existovaly některé profesionální baseballové týmy. Dílčí výraz \r?\Z v regulárním výrazu ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\Z je splněn na konci řetězce a také na konci řetězce, který končí \n nebo \r\n. V důsledku toho každý prvek v poli odpovídá vzoru regulárního výrazu.

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.

Jen na konci řetězce: \z

Ukotvení \z určuje, že na konci vstupního řetězce musí dojít ke shodě. $ Podobně jako prvek \z jazyka RegexOptions.Multiline ignoruje tuto možnost. Na rozdíl od elementu \Z\z jazyka není znakem na konci řetězce spokojen \n . Proto může odpovídat pouze konci vstupního řetězce.

Následující příklad používá kotvu \z v regulárním výrazu, který je jinak identický s příkladem v předchozí části, který extrahuje informace o letech, během kterých existovaly některé profesionální baseballové týmy. Příklad se pokusí spárovat každý z pěti prvků v řetězcovém poli se vzorem ^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+\r?\zregulárního výrazu . Dva řetězce končí znakem návratu na začátek řádku a znakem odřádkování, jeden končí znakem odřádkování a dvěma konci bez návratu na začátek řádku ani znakem odřádkování. Jak ukazuje výstup, odpovídají vzoru pouze řetězce bez znaku návratu na začátek řádku nebo odřádkování.

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.

Souvislé porovnávání: \G

Ukotvení \G určuje, že shoda musí nastat v okamžiku, kdy předchozí shoda skončila, nebo pokud nedošlo k žádné předchozí shodě, na pozici v řetězci, kde bylo zahájeno párování. Pokud použijete toto ukotvení s metodou Regex.Matches nebo Match.NextMatch metodou, zajistí, že všechny shody jsou souvislé.

Tip

Obvykle umístíte kotvu \G na levý konec vzoru. V neobvyklém případě, že provádíte hledání zprava doleva, umístěte \G ukotvení na pravý konec vzoru.

Následující příklad používá regulární výraz k extrakci názvů druhů hlásek z řetězce s oddělovači.

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

Regulární výraz \G(\w+\s?\w*),? se interpretuje, jak je znázorněno v následující tabulce.

Vzor Popis
\G Začněte tím, kde skončila poslední shoda.
\w+ Porovná jeden nebo více znaků slova.
\s? Porovná žádnou nebo jednu mezeru.
\w* Porovná žádný nebo více znaků slova.
(\w+\s?\w*) Porovná jeden nebo více znaků slova následovaných nulou nebo jednou mezerou, za kterou následuje nula nebo více znaků slova. Toto je první zachytávající skupina.
,? Porovná žádný nebo jeden výskyt literálového znaku čárky.

Na hranici slova: \b

Ukotvení \b určuje, že shoda se musí nacházet na hranici mezi znakem slova ( \w element jazyka) a neslovným znakem ( \W prvek jazyka). Znaky slova se skládají z alfanumerických znaků a podtržítka; Neslovný znak je libovolný znak, který není alfanumerický ani podtržítko. (Další informace najdete v tématu Třídy znaků.) Shoda může nastat také na hranici slova na začátku nebo na konci řetězce.

Ukotvení \b se často používá k zajištění toho, aby dílčí výraz odpovídal celému slovu místo jenom začátku nebo konce slova. Toto použití ilustruje regulární výraz \bare\w*\b v následujícím příkladu. Odpovídá libovolnému slovu, které začíná podřetězníkem "are". Výstup z příkladu také ukazuje, že \b odpovídá začátku i konci vstupního řetězce.

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

Vzor regulárního výrazu je interpretován, jak je znázorněno v následující tabulce.

Vzor Popis
\b Začne porovnání na hranici slova.
are Porovná podřetěžce "are".
\w* Porovná žádný nebo více znaků slova.
\b Ukončí porovnání na hranici slova.

Mimo hranice slova: \B

Ukotvení \B určuje, že shoda nesmí nacházet na hranici slova. Je to opak kotvy \b .

Následující příklad používá ukotvení \B k vyhledání výskytů podřetědce "qu" ve slově. Vzor \Bqu\w+ regulárního výrazu odpovídá podřetězdci, která začíná řetězcem "qu", který nezačíná slovem a který pokračuje na konec slova.

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

Vzor regulárního výrazu je interpretován, jak je znázorněno v následující tabulce.

Vzor Popis
\B Nezačínejte shodu na hranici slova.
qu Porovná podřetěžce "qu".
\w+ Porovná jeden nebo více znaků slova.

Viz také