Aracılığıyla paylaş


Normal ifade seçenekleri

Varsayılan olarak, giriş dizesinin normal ifade desenindeki değişmez karakterlerle karşılaştırılması büyük/küçük harfe duyarlıdır, normal ifade desenindeki boşluk değişmez boşluk karakterleri olarak yorumlanır ve normal ifadedeki grupları yakalama işlemi örtük olarak ve açıkça adlandırılır. Normal ifade seçeneklerini belirterek bunları ve varsayılan normal ifade davranışının diğer çeşitli yönlerini değiştirebilirsiniz. Aşağıdaki tabloda listelenen bu seçeneklerden bazıları, düzenli ifade deseni içinde satır içi olarak eklenebilir veya bir sınıf yapıcısına ya da statik desen eşleştirme yöntemine bir sabit listesi değeri olarak System.Text.RegularExpressions.RegexSystem.Text.RegularExpressions.RegexOptions verilebilir.

RegexOptions üye Satır içi karakter Etki Daha Fazla Bilgi
None Kullanılamaz Varsayılan davranışı kullanın. Varsayılan seçenekler
IgnoreCase i Büyük küçük harf duyarlı eşleme kullanın. Büyük/küçük harfe duyarlı olmayan eşleştirme
Multiline m Çok satırlı modu kullanın, burada her satırın başlangıcını ve sonunu ^ ve $ ile belirtin (giriş dizesinin başlangıcı ve sonu yerine). Çok satırlı mod
Singleline s Tek satır modunu kullanın, bu modda nokta (.) \n hariç her karakterle eşleşir. Tek satırlı mod
ExplicitCapture n Adsız grupları yakalamayın. Yalnızca geçerli yakalamalar, form (?<adı> alt ifadesinin açıkça adlandırılmış veya numaralandırılmış gruplarıdır.) Yalnızca açık yakalama modunu etkinleştir
Compiled Kullanılamaz Normal ifadeyi bir derlemeye derleyin. Derlenmiş normal ifadeler
IgnorePatternWhitespace x Düzen dışı boşlukları desenden dışlayın ve sayı işaretinden (# sonra) açıklamaları etkinleştirin. Beyaz boşluğu yoksay
RightToLeft Kullanılamaz Arama yönünü değiştirin. Arama, soldan sağa değil, sağdan sola taşınır. Sağdan sola modu
ECMAScript Kullanılamaz İfade için ECMAScript uyumlu davranışı etkinleştirin. ECMAScript eşleştirme davranışı
CultureInvariant Kullanılamaz Dildeki kültürel farklılıkları yoksayın. Sabit kültürü kullanarak karşılaştırma
NonBacktracking Kullanılamaz Geri izlemeyi önleyen ve girişin uzunluğunda doğrusal zaman işlemeyi garanti eden bir yaklaşım kullanarak eşleştirin. (.NET 7 ve sonraki sürümlerde kullanılabilir.) Geri izlememe modu

Seçenekleri belirtme

Normal ifadeler için seçenekleri üç yoldan biriyle belirtebilirsiniz:

  • options parametresinde, bir System.Text.RegularExpressions.Regex sınıfının oluşturucusu veya statik (Visual Basic'te Shared) desen eşleştirme yöntemi gibi Regex(String, RegexOptions) veya Regex.Match(String, String, RegexOptions). options parametresi, numaralandırılmış değerlerin System.Text.RegularExpressions.RegexOptions bit düzeyinde VEYA işlemiyle oluşan bir birleşimidir.

    Bir sınıf oluşturucusunun Regex parametresi kullanılarak bir options örneğe seçenekler sağlandığında, seçenekler özelliğine System.Text.RegularExpressions.RegexOptions atanır. Ancak, System.Text.RegularExpressions.RegexOptions özelliği normal ifade desenindeki satır içi seçenekleri yansıtmaz.

    Aşağıdaki örnek, bir gösterim sağlar. "Kelimenin 'd' harfiyle başlamasını tanımlarken büyük/küçük harfe duyarsız eşleştirmeyi ve desen boşluklarını yoksaymayı etkinleştirmek için, options parametresini Regex.Match(String, String, RegexOptions) yönteminde kullanır."

    string pattern = @"d \w+ \s";
    string input = "Dogs are decidedly good pets.";
    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace;
    
    foreach (Match match in Regex.Matches(input, pattern, options))
        Console.WriteLine($"'{match.Value}// found at index {match.Index}.");
    // The example displays the following output:
    //    'Dogs // found at index 0.
    //    'decidedly // found at index 9.
    
    Dim pattern As String = "d \w+ \s"
    Dim input As String = "Dogs are decidedly good pets."
    Dim options As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace
    
    For Each match As Match In Regex.Matches(input, pattern, options)
        Console.WriteLine("'{0}' found at index {1}.", match.Value, match.Index)
    Next
    ' The example displays the following output:
    '    'Dogs ' found at index 0.
    '    'decidedly ' found at index 9.      
    
  • Söz dizimi (?imnsx-imnsx)ile normal ifade deseninde satır içi seçenekleri uygulayarak. seçenek, seçeneğin tanımlandığı noktadan desenin sonuna veya seçeneğin başka bir satır içi seçenek tarafından tanımlanmadığı noktaya kadar desene uygulanır. System.Text.RegularExpressions.RegexOptions örneğinin Regex özelliğinin bu satır içi seçenekleri yansıtmadığını unutmayın. Daha fazla bilgi için Çeşitli Yapılar konusuna bakın.

    Aşağıdaki örnek, bir gösterim sağlar. Yerleşik seçenekleri kullanarak büyük/küçük harfe duyarsız eşleştirmeyi etkinleştirir ve "d" harfiyle başlayan sözcükleri tanımlarken desendeki boşlukları göz ardı eder.

    string pattern = @"(?ix) d \w+ \s";
    string input = "Dogs are decidedly good pets.";
    
    foreach (Match match in Regex.Matches(input, pattern))
        Console.WriteLine($"'{match.Value}// found at index {match.Index}.");
    // The example displays the following output:
    //    'Dogs // found at index 0.
    //    'decidedly // found at index 9.
    
    Dim pattern As String = "\b(?ix) d \w+ \s"
    Dim input As String = "Dogs are decidedly good pets."
    
    For Each match As Match In Regex.Matches(input, pattern)
        Console.WriteLine("'{0}' found at index {1}.", match.Value, match.Index)
    Next
    ' The example displays the following output:
    '    'Dogs ' found at index 0.
    '    'decidedly ' found at index 9.      
    
  • Belirli bir gruplandırma yapısında satır içi seçenekleri, düzenli ifade deseni içinde (?imnsx-imnsx:alt ifade) söz dizimi ile uygulayarak. Seçenekler kümesinin başında bir işaret olmaması, kümenin açılmasını sağlar; seçenekler kümesinin başındaki eksi işareti ise kümenin kapanmasını sağlar. (? dil yapısının söz diziminin, seçeneklerin etkin veya devre dışı olması fark etmeksizin gerekli olan sabit bir parçasıdır.) bu seçenek yalnızca bu grup için geçerlidir. Daha fazla bilgi için bkz . Gruplandırma Yapıları.

    Aşağıdaki örnek, bir gösterim sağlar. Büyük/küçük harfe duyarsız eşleştirmeyi etkinleştirmek ve "d" harfiyle başlayan sözcükleri tanımlarken desen boşluklarını yoksaymak için bir gruplandırma yapısındaki satır içi seçenekleri kullanır.

    string pattern = @"\b(?ix: d \w+)\s";
    string input = "Dogs are decidedly good pets.";
    
    foreach (Match match in Regex.Matches(input, pattern))
        Console.WriteLine($"'{match.Value}// found at index {match.Index}.");
    // The example displays the following output:
    //    'Dogs // found at index 0.
    //    'decidedly // found at index 9.
    
    Dim pattern As String = "\b(?ix: d \w+)\s"
    Dim input As String = "Dogs are decidedly good pets."
    
    For Each match As Match In Regex.Matches(input, pattern)
        Console.WriteLine("'{0}' found at index {1}.", match.Value, match.Index)
    Next
    ' The example displays the following output:
    '    'Dogs ' found at index 0.
    '    'decidedly ' found at index 9.      
    

Seçenekler satır içinde belirtilirse, bir seçenek veya seçenek kümesinden önce bir eksi işareti (-) bu seçenekleri kapatır. Örneğin, satır içi yapısı (?ix-ms) ve RegexOptions.IgnoreCase seçeneklerini açar ve RegexOptions.IgnorePatternWhitespace ve RegexOptions.Multiline seçeneklerini kapatır. Tüm normal ifade seçenekleri varsayılan olarak kapalıdır.

Not

Bir oluşturucunun veya yöntem çağrısının options parametresinde belirtilen normal ifade seçenekleri, normal ifade deseninde satır içinde belirtilen seçeneklerle çakışıyorsa, satır içi seçenekler kullanılır.

Aşağıdaki beş normal ifade seçeneği hem options parametresi hem de satır içi ile ayarlanabilir:

Aşağıdaki beş normal ifade seçeneği parametresi kullanılarak options ayarlanabilir ancak satır içinde ayarlanamaz:

Seçenekleri belirleme

Salt okunur Regex özelliğin değerini alarak bir Regex.Options nesnenin örneği oluşturulduğunda hangi seçeneklerin sağlandığını belirleyebilirsiniz.

ilgili özelliğin RegexOptions.None dışında herhangi bir seçeneğin varlığını test etmek için, Regex.Options değeri ile ilgilendiğiniz RegexOptions değeri üzerinden bir AND işlemi gerçekleştirin. Ardından sonucun bu RegexOptions değere eşit olup olmadığını test edin. Aşağıdaki örnek, RegexOptions.IgnoreCase seçeneğinin ayarlanıp ayarlanmadığını sınar.

if ((rgx.Options & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
    Console.WriteLine("Case-insensitive pattern comparison.");
else
    Console.WriteLine("Case-sensitive pattern comparison.");
If (rgx.Options And RegexOptions.IgnoreCase) = RegexOptions.IgnoreCase Then
    Console.WriteLine("Case-insensitive pattern comparison.")
Else
    Console.WriteLine("Case-sensitive pattern comparison.")
End If

RegexOptions.None ile ilgili test yapmak için, aşağıdaki örnekte gösterildiği gibi, özellik değeri Regex.OptionsRegexOptions.None'e eşit mi belirleyin.

if (rgx.Options == RegexOptions.None)
    Console.WriteLine("No options have been set.");
If rgx.Options = RegexOptions.None Then
    Console.WriteLine("No options have been set.")
End If

Aşağıdaki bölümlerde.NET'te normal ifade tarafından desteklenen seçenekler listelenmiştir.

Varsayılan seçenekler

RegexOptions.None seçeneği, hiçbir seçeneğin belirtilmediğinden ve normal ifade altyapısının varsayılan davranışını kullandığını gösterir. Bunlar arasında aşağıdakiler yer alır:

  • Desen, ECMAScript normal ifadesi yerine kurallı olarak yorumlanır.

  • Normal ifade deseni, giriş dizesinde soldan sağa eşleştirilir.

  • Karşılaştırmalar büyük/küçük harfe duyarlıdır.

  • ^ ve $ dil öğeleri giriş dizesinin başlangıcını ve sonunu gösterir. Giriş dizesinin sonu, sondaki yeni satır \n karakteri olabilir.

  • . Dil öğesi dışındaki \nher karakterle eşleşir.

  • Düzenli ifade deseninde yer alan herhangi bir boşluk, tam bir boşluk karakteri olarak yorumlanır.

  • Geçerli kültürün kuralları, desen giriş dizesiyle karşılaştırılırken kullanılır.

  • Normal ifade desenindeki grupları yakalama örtük ve açıktır.

Not

Seçeneğinin RegexOptions.None satır içi eşdeğeri yoktur. Normal ifade seçenekleri satır içinde uygulandığında, varsayılan davranış belirli bir seçenek kapatılarak seçenek bazında geri yüklenir. Örneğin, (?i) büyük/küçük harfe duyarlı olmayan karşılaştırmayı açar ve (?-i) varsayılan büyük/küçük harfe duyarlı karşılaştırmayı geri yükler.

RegexOptions.None seçeneği normal ifade altyapısının varsayılan davranışını temsil ettiğinden, yöntem çağrısında nadiren belirtilir. Bunun yerine parametresi olmayan bir options oluşturucu veya statik desen eşleştirme yöntemi çağrılır.

Büyük/küçük harfe duyarlı olmayan eşleştirme

IgnoreCase seçeneği veya i satır içi seçeneği, büyük/küçük harfe duyarsız eşleştirme sağlar. Varsayılan olarak, geçerli kültürün büyük/küçük harf kuralları kullanılır.

Aşağıdaki örnek, \bthe\w*\b"the" ile başlayan tüm sözcüklerle eşleşen bir normal ifade deseni tanımlar. yöntemine Match yapılan ilk çağrı varsayılan büyük/küçük harfe duyarlı karşılaştırmayı kullandığından çıkış, cümleyi başlayan "The" dizesinin eşleşmediğini gösterir. Match yöntemi, IgnoreCase olarak ayarlanmış seçeneklerle çağrıldığında eşleştirilir.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\bthe\w*\b";
      string input = "The man then told them about that event.";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine($"Found {match.Value} at index {match.Index}.");

      Console.WriteLine();
      foreach (Match match in Regex.Matches(input, pattern,
                                            RegexOptions.IgnoreCase))
         Console.WriteLine($"Found {match.Value} at index {match.Index}.");
   }
}
// The example displays the following output:
//       Found then at index 8.
//       Found them at index 18.
//
//       Found The at index 0.
//       Found then at index 8.
//       Found them at index 18.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\bthe\w*\b"
        Dim input As String = "The man then told them about that event."
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index)
        Next
        Console.WriteLine()
        For Each match As Match In Regex.Matches(input, pattern, _
                                                 RegexOptions.IgnoreCase)
            Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index)
        Next
    End Sub
End Module
' The example displays the following output:
'       Found then at index 8.
'       Found them at index 18.
'       
'       Found The at index 0.
'       Found then at index 8.
'       Found them at index 18.

Aşağıdaki örnek, harf duyarlılığı olmadan karşılaştırma yapabilmek için parametre yerine satır içi seçenekler kullanarak önceki örnekteki options normal ifade desenini değiştirir. İlk desen, yalnızca "the" dizesindeki "t" harfine uygulanan bir gruplandırma yapısında büyük/küçük harfe duyarsız seçeneğini tanımlar. Seçenek yapısı desenin başında gerçekleştiğinden, ikinci desen büyük/küçük harfe duyarsız seçeneğini normal ifadenin tamamına uygular.

using System;
using System.Text.RegularExpressions;

public class CaseExample
{
    public static void Main()
    {
        string pattern = @"\b(?i:t)he\w*\b";
        string input = "The man then told them about that event.";
        foreach (Match match in Regex.Matches(input, pattern))
            Console.WriteLine($"Found {match.Value} at index {match.Index}.");

        Console.WriteLine();
        pattern = @"(?i)\bthe\w*\b";
        foreach (Match match in Regex.Matches(input, pattern,
                                              RegexOptions.IgnoreCase))
            Console.WriteLine($"Found {match.Value} at index {match.Index}.");
    }
}
// The example displays the following output:
//       Found The at index 0.
//       Found then at index 8.
//       Found them at index 18.
//
//       Found The at index 0.
//       Found then at index 8.
//       Found them at index 18.
Imports System.Text.RegularExpressions

Module CaseExample
    Public Sub Main()
        Dim pattern As String = "\b(?i:t)he\w*\b"
        Dim input As String = "The man then told them about that event."
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index)
        Next
        Console.WriteLine()
        pattern = "(?i)\bthe\w*\b"
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index)
        Next
    End Sub
End Module

' The example displays the following output:
'       Found The at index 0.
'       Found then at index 8.
'       Found them at index 18.
'       
'       Found The at index 0.
'       Found then at index 8.
'       Found them at index 18.

Çok satırlı mod

RegexOptions.Multiline seçeneği veya m satır içi seçeneği, normal ifade altyapısının birden çok satırdan oluşan bir giriş dizesini işlemesini sağlar. ^ ve $ dil öğelerinin yorumunu, giriş dizisinin başlangıcı ve sonu yerine bir satırın başlangıcını ve sonunu gösterecek şekilde değiştirir.

Varsayılan olarak, $, yalnızca giriş dizesinin sonunda sağlanır. Eğer RegexOptions.Multiline seçeneğini belirlerseniz, bu seçenek yeni satır karakteri (\n) veya giriş dizesinin sonu tarafından karşılanır.

Hiçbir durumda da $ satır başı ve satır besleme karakter bileşimini tanımaz\r\n. $ her zaman herhangi bir satır başı (\r) yoksayar. Maçınızı \r\n veya \n ile sonlandırmak için yalnızca \r?$ yerine $ alt ifadesini kullanın. Bunun, eşleşmenin \r bir kısmını oluşturacağını unutmayın.

Aşağıdaki örnek, bowling oyuncularının adlarını ve puanlarını alır ve bunları azalan sırayla sıralayan bir SortedList<TKey,TValue> koleksiyona ekler. Matches yöntemi iki kez çağrılır. İlk yöntem çağrısında normal ifadedir ^(\w+)\s(\d+)$ ve hiçbir seçenek ayarlanmadı. Çıktıda gösterildiği gibi, normal ifade altyapısı giriş dizesinin başlangıcı ve sonuyla birlikte giriş deseniyle eşleşemediğinden eşleşme bulunmaz. İkinci yöntem çağrısında normal ifade olarak ^(\w+)\s(\d+)\r?$ değiştirilir ve seçenekler olarak RegexOptions.Multilineayarlanır. Çıktıda gösterildiği gibi, adlar ve puanlar başarıyla eşleştirilir ve puanlar azalan sırada görüntülenir.

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

public class Multiline1Example
{
    public static void Main()
    {
        SortedList<int, string> scores = new SortedList<int, string>(new DescendingComparer1<int>());

        string input = "Joe 164\n" +
                       "Sam 208\n" +
                       "Allison 211\n" +
                       "Gwen 171\n";
        string pattern = @"^(\w+)\s(\d+)$";
        bool matched = false;

        Console.WriteLine("Without Multiline option:");
        foreach (Match match in Regex.Matches(input, pattern))
        {
            scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);
            matched = true;
        }
        if (!matched)
            Console.WriteLine("   No matches.");
        Console.WriteLine();

        // Redefine pattern to handle multiple lines.
        pattern = @"^(\w+)\s(\d+)\r*$";
        Console.WriteLine("With multiline option:");
        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Multiline))
            scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);

        // List scores in descending order.
        foreach (KeyValuePair<int, string> score in scores)
            Console.WriteLine($"{score.Value}: {score.Key}");
    }
}

public class DescendingComparer1<T> : IComparer<T>
{
    public int Compare(T x, T y)
    {
        return Comparer<T>.Default.Compare(x, y) * -1;
    }
}
// The example displays the following output:
//   Without Multiline option:
//      No matches.
//
//   With multiline option:
//   Allison: 211
//   Sam: 208
//   Gwen: 171
//   Joe: 164
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Multiline1Example
    Public Sub Main()
        Dim scores As New SortedList(Of Integer, String)(New DescendingComparer1(Of Integer)())

        Dim input As String = "Joe 164" + vbCrLf +
                              "Sam 208" + vbCrLf +
                              "Allison 211" + vbCrLf +
                              "Gwen 171" + vbCrLf
        Dim pattern As String = "^(\w+)\s(\d+)$"
        Dim matched As Boolean = False

        Console.WriteLine("Without Multiline option:")
        For Each match As Match In Regex.Matches(input, pattern)
            scores.Add(CInt(match.Groups(2).Value), match.Groups(1).Value)
            matched = True
        Next
        If Not matched Then Console.WriteLine("   No matches.")
        Console.WriteLine()

        ' Redefine pattern to handle multiple lines.
        pattern = "^(\w+)\s(\d+)\r*$"
        Console.WriteLine("With multiline option:")
        For Each match As Match In Regex.Matches(input, pattern, RegexOptions.Multiline)
            scores.Add(CInt(match.Groups(2).Value), match.Groups(1).Value)
        Next
        ' List scores in descending order. 
        For Each score As KeyValuePair(Of Integer, String) In scores
            Console.WriteLine("{0}: {1}", score.Value, score.Key)
        Next
    End Sub
End Module

Public Class DescendingComparer1(Of T) : Implements IComparer(Of T)
    Public Function Compare(x As T, y As T) As Integer _
           Implements IComparer(Of T).Compare
        Return Comparer(Of T).Default.Compare(x, y) * -1
    End Function
End Class
' The example displays the following output:
'    Without Multiline option:
'       No matches.
'    
'    With multiline option:
'    Allison: 211
'    Sam: 208
'    Gwen: 171
'    Joe: 164

Normal ifade deseni ^(\w+)\s(\d+)\r*$ aşağıdaki tabloda gösterildiği gibi tanımlanır.

Desen Açıklama
^ Satırın başlangıcından başlayın.
(\w+) Bir veya daha fazla sözcük karakteri eşleştir. İlk yakalama grubu budur.
\s Bir boşluk karakteri ile eşleştirin.
(\d+) Bir veya daha fazla ondalık basamağı eşleştirin. Bu ikinci yakalama grubudur.
\r? Sıfır veya bir satır başı karakterini bulun ve eşleştirin.
$ Satırın sonunda bitir.

Aşağıdaki örnek, çok satırlı seçeneği ayarlamak için satır içi seçeneğini (?m) kullanması dışında öncekine eşdeğerdir.

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

public class Multiline2Example
{
    public static void Main()
    {
        SortedList<int, string> scores = new SortedList<int, string>(new DescendingComparer<int>());

        string input = "Joe 164\n" +
                       "Sam 208\n" +
                       "Allison 211\n" +
                       "Gwen 171\n";
        string pattern = @"(?m)^(\w+)\s(\d+)\r*$";

        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Multiline))
            scores.Add(Convert.ToInt32(match.Groups[2].Value), match.Groups[1].Value);

        // List scores in descending order.
        foreach (KeyValuePair<int, string> score in scores)
            Console.WriteLine($"{score.Value}: {score.Key}");
    }
}

public class DescendingComparer<T> : IComparer<T>
{
    public int Compare(T x, T y)
    {
        return Comparer<T>.Default.Compare(x, y) * -1;
    }
}
// The example displays the following output:
//    Allison: 211
//    Sam: 208
//    Gwen: 171
//    Joe: 164
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Multiline2Example
    Public Sub Main()
        Dim scores As New SortedList(Of Integer, String)(New DescendingComparer(Of Integer)())

        Dim input As String = "Joe 164" + vbCrLf +
                              "Sam 208" + vbCrLf +
                              "Allison 211" + vbCrLf +
                              "Gwen 171" + vbCrLf
        Dim pattern As String = "(?m)^(\w+)\s(\d+)\r*$"

        For Each match As Match In Regex.Matches(input, pattern, RegexOptions.Multiline)
            scores.Add(CInt(match.Groups(2).Value), match.Groups(1).Value)
        Next
        ' List scores in descending order. 
        For Each score As KeyValuePair(Of Integer, String) In scores
            Console.WriteLine("{0}: {1}", score.Value, score.Key)
        Next
    End Sub
End Module

Public Class DescendingComparer(Of T) : Implements IComparer(Of T)
    Public Function Compare(x As T, y As T) As Integer _
           Implements IComparer(Of T).Compare
        Return Comparer(Of T).Default.Compare(x, y) * -1
    End Function
End Class
' The example displays the following output:
'    Allison: 211
'    Sam: 208
'    Gwen: 171
'    Joe: 164

Tek satırlı mod

RegexOptions.Singleline seçeneği veya s satır içi seçeneği, normal ifade altyapısının giriş dizesini tek bir satırdan oluşuyor gibi ele almasına neden olur. Bu, nokta (.) dil öğesinin davranışını, yeni satır karakteri dışındaki her karakter yerine her karakterle eşleşecek şekilde değiştirir.

Aşağıdaki örnek, . seçeneğini kullandığınızda RegexOptions.Singleline dil öğesinin davranışının nasıl değiştiğini göstermektedir. Normal ifade ^.+ dizenin başında başlar ve her karakterle eşleşir. Varsayılan olarak, eşleşme ilk satırın sonunda biter; normal ifade deseni satır başı karakteri ile \r eşleşir, ancak \n ile eşleşmez. RegexOptions.Singleline seçeneği giriş dizesinin tamamını tek bir satır olarak yorumladığı için, dahil olmak üzere \ngiriş dizesindeki her karakterle eşleşir.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "^.+";
      string input = "This is one line and" + Environment.NewLine + "this is the second.";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine(Regex.Escape(match.Value));

      Console.WriteLine();
      foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Singleline))
         Console.WriteLine(Regex.Escape(match.Value));
   }
}
// The example displays the following output:
//       This\ is\ one\ line\ and\r
//
//       This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "^.+"
        Dim input As String = "This is one line and" + vbCrLf + "this is the second."
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine(Regex.Escape(match.Value))
        Next
        Console.WriteLine()
        For Each match As Match In Regex.Matches(input, pattern, RegexOptions.SingleLine)
            Console.WriteLine(Regex.Escape(match.Value))
        Next
    End Sub
End Module
' The example displays the following output:
'       This\ is\ one\ line\ and\r
'       
'       This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.

Aşağıdaki örnek, tek satır modunu etkinleştirmek için satır içi seçeneğini (?s) kullanması dışında öncekine eşdeğerdir.

using System;
using System.Text.RegularExpressions;

public class SingleLineExample
{
    public static void Main()
    {
        string pattern = "(?s)^.+";
        string input = "This is one line and" + Environment.NewLine + "this is the second.";

        foreach (Match match in Regex.Matches(input, pattern))
            Console.WriteLine(Regex.Escape(match.Value));
    }
}
// The example displays the following output:
//       This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
Imports System.Text.RegularExpressions

Module SingleLineExample
    Public Sub Main()
        Dim pattern As String = "(?s)^.+"
        Dim input As String = "This is one line and" + vbCrLf + "this is the second."

        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine(Regex.Escape(match.Value))
        Next
    End Sub
End Module
' The example displays the following output:
'       This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.

Yalnızca açık yakalamalar

Varsayılan olarak, yakalama grupları normal ifade deseninde parantezlerin kullanılmasıyla tanımlanır. Adlandırılmış gruplara, (?<ad>alt ifade) dili seçeneği ile bir ad veya numara atanırken, adsız gruplara dizin ile erişilebilir. nesnesinde GroupCollection , adlandırılmamış gruplar adlandırılmış grupların önünde yer alır.

Gruplandırma yapıları genellikle yalnızca birden çok dil öğesine niceleyici uygulamak için kullanılır ve yakalanan alt dizeler ilgi çekici değildir. Örneğin, aşağıdaki normal ifade:

\b\(?((\w+),?\s?)+[\.!?]\)?

yalnızca bir belgeden nokta, ünlem işareti veya soru işaretiyle biten tümceleri ayıklamak için tasarlanmıştır; yalnızca sonuçta elde edilen tümce (nesne tarafından Match temsil edilir) ilgi çekicidir. Koleksiyondaki tek tek sözcükler yoktur.

Normal ifade motorunun hem GroupCollection hem de CaptureCollection koleksiyon nesnelerini doldurması gerektiğinden, daha sonra kullanılmayan grupları yakalamak pahalı olabilir. Alternatif olarak, yalnızca geçerli yakalamaların RegexOptions.ExplicitCapturen(?< alt ifade> yapısı tarafından belirlenen açıkça adlandırılmış veya numaralandırılmış gruplar olduğunu belirtmek için ya seçeneğini ya da ) satır içi seçeneğini kullanabilirsiniz.

Aşağıdaki örnek, \b\(?((\w+),?\s?)+[\.!?]\)? yöntemi Match seçeneği ile ve seçeneği olmadan çağrıldığında RegexOptions.ExplicitCapture normal ifade deseni tarafından döndürülen eşleşmeler hakkında bilgi görüntüler. İlk yöntem çağrısının çıktısında gösterildiği gibi, düzenli ifade motoru, yakalanan alt dizeler hakkındaki bilgilerle GroupCollection ve CaptureCollection koleksiyon nesnelerini tamamen doldurur. İkinci yöntem optionsRegexOptions.ExplicitCapture olarak ayarlandığında çağrıldığı için, gruplarla ilgili bilgileri yakalamaz.

using System;
using System.Text.RegularExpressions;

public class Explicit1Example
{
    public static void Main()
    {
        string input = "This is the first sentence. Is it the beginning " +
                       "of a literary masterpiece? I think not. Instead, " +
                       "it is a nonsensical paragraph.";
        string pattern = @"\b\(?((?>\w+),?\s?)+[\.!?]\)?";
        Console.WriteLine("With implicit captures:");
        foreach (Match match in Regex.Matches(input, pattern))
        {
            Console.WriteLine($"The match: {match.Value}");
            int groupCtr = 0;
            foreach (Group group in match.Groups)
            {
                Console.WriteLine($"   Group {groupCtr}: {group.Value}");
                groupCtr++;
                int captureCtr = 0;
                foreach (Capture capture in group.Captures)
                {
                    Console.WriteLine($"      Capture {captureCtr}: {capture.Value}");
                    captureCtr++;
                }
            }
        }
        Console.WriteLine();
        Console.WriteLine("With explicit captures only:");
        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.ExplicitCapture))
        {
            Console.WriteLine($"The match: {match.Value}");
            int groupCtr = 0;
            foreach (Group group in match.Groups)
            {
                Console.WriteLine($"   Group {groupCtr}: {group.Value}");
                groupCtr++;
                int captureCtr = 0;
                foreach (Capture capture in group.Captures)
                {
                    Console.WriteLine($"      Capture {captureCtr}: {capture.Value}");
                    captureCtr++;
                }
            }
        }
    }
}
// The example displays the following output:
//    With implicit captures:
//    The match: This is the first sentence.
//       Group 0: This is the first sentence.
//          Capture 0: This is the first sentence.
//       Group 1: sentence
//          Capture 0: This
//          Capture 1: is
//          Capture 2: the
//          Capture 3: first
//          Capture 4: sentence
//       Group 2: sentence
//          Capture 0: This
//          Capture 1: is
//          Capture 2: the
//          Capture 3: first
//          Capture 4: sentence
//    The match: Is it the beginning of a literary masterpiece?
//       Group 0: Is it the beginning of a literary masterpiece?
//          Capture 0: Is it the beginning of a literary masterpiece?
//       Group 1: masterpiece
//          Capture 0: Is
//          Capture 1: it
//          Capture 2: the
//          Capture 3: beginning
//          Capture 4: of
//          Capture 5: a
//          Capture 6: literary
//          Capture 7: masterpiece
//       Group 2: masterpiece
//          Capture 0: Is
//          Capture 1: it
//          Capture 2: the
//          Capture 3: beginning
//          Capture 4: of
//          Capture 5: a
//          Capture 6: literary
//          Capture 7: masterpiece
//    The match: I think not.
//       Group 0: I think not.
//          Capture 0: I think not.
//       Group 1: not
//          Capture 0: I
//          Capture 1: think
//          Capture 2: not
//       Group 2: not
//          Capture 0: I
//          Capture 1: think
//          Capture 2: not
//    The match: Instead, it is a nonsensical paragraph.
//       Group 0: Instead, it is a nonsensical paragraph.
//          Capture 0: Instead, it is a nonsensical paragraph.
//       Group 1: paragraph
//          Capture 0: Instead,
//          Capture 1: it
//          Capture 2: is
//          Capture 3: a
//          Capture 4: nonsensical
//          Capture 5: paragraph
//       Group 2: paragraph
//          Capture 0: Instead
//          Capture 1: it
//          Capture 2: is
//          Capture 3: a
//          Capture 4: nonsensical
//          Capture 5: paragraph
//
//    With explicit captures only:
//    The match: This is the first sentence.
//       Group 0: This is the first sentence.
//          Capture 0: This is the first sentence.
//    The match: Is it the beginning of a literary masterpiece?
//       Group 0: Is it the beginning of a literary masterpiece?
//          Capture 0: Is it the beginning of a literary masterpiece?
//    The match: I think not.
//       Group 0: I think not.
//          Capture 0: I think not.
//    The match: Instead, it is a nonsensical paragraph.
//       Group 0: Instead, it is a nonsensical paragraph.
//          Capture 0: Instead, it is a nonsensical paragraph.
Imports System.Text.RegularExpressions

Module Explicit1Example
    Public Sub Main()
        Dim input As String = "This is the first sentence. Is it the beginning " +
                              "of a literary masterpiece? I think not. Instead, " +
                              "it is a nonsensical paragraph."
        Dim pattern As String = "\b\(?((?>\w+),?\s?)+[\.!?]\)?"
        Console.WriteLine("With implicit captures:")
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("The match: {0}", match.Value)
            Dim groupCtr As Integer = 0
            For Each group As Group In match.Groups
                Console.WriteLine("   Group {0}: {1}", groupCtr, group.Value)
                groupCtr += 1
                Dim captureCtr As Integer = 0
                For Each capture As Capture In group.Captures
                    Console.WriteLine("      Capture {0}: {1}", captureCtr, capture.Value)
                    captureCtr += 1
                Next
            Next
        Next
        Console.WriteLine()
        Console.WriteLine("With explicit captures only:")
        For Each match As Match In Regex.Matches(input, pattern, RegexOptions.ExplicitCapture)
            Console.WriteLine("The match: {0}", match.Value)
            Dim groupCtr As Integer = 0
            For Each group As Group In match.Groups
                Console.WriteLine("   Group {0}: {1}", groupCtr, group.Value)
                groupCtr += 1
                Dim captureCtr As Integer = 0
                For Each capture As Capture In group.Captures
                    Console.WriteLine("      Capture {0}: {1}", captureCtr, capture.Value)
                    captureCtr += 1
                Next
            Next
        Next
    End Sub
End Module
' The example displays the following output:
'    With implicit captures:
'    The match: This is the first sentence.
'       Group 0: This is the first sentence.
'          Capture 0: This is the first sentence.
'       Group 1: sentence
'          Capture 0: This
'          Capture 1: is
'          Capture 2: the
'          Capture 3: first
'          Capture 4: sentence
'       Group 2: sentence
'          Capture 0: This
'          Capture 1: is
'          Capture 2: the
'          Capture 3: first
'          Capture 4: sentence
'    The match: Is it the beginning of a literary masterpiece?
'       Group 0: Is it the beginning of a literary masterpiece?
'          Capture 0: Is it the beginning of a literary masterpiece?
'       Group 1: masterpiece
'          Capture 0: Is
'          Capture 1: it
'          Capture 2: the
'          Capture 3: beginning
'          Capture 4: of
'          Capture 5: a
'          Capture 6: literary
'          Capture 7: masterpiece
'       Group 2: masterpiece
'          Capture 0: Is
'          Capture 1: it
'          Capture 2: the
'          Capture 3: beginning
'          Capture 4: of
'          Capture 5: a
'          Capture 6: literary
'          Capture 7: masterpiece
'    The match: I think not.
'       Group 0: I think not.
'          Capture 0: I think not.
'       Group 1: not
'          Capture 0: I
'          Capture 1: think
'          Capture 2: not
'       Group 2: not
'          Capture 0: I
'          Capture 1: think
'          Capture 2: not
'    The match: Instead, it is a nonsensical paragraph.
'       Group 0: Instead, it is a nonsensical paragraph.
'          Capture 0: Instead, it is a nonsensical paragraph.
'       Group 1: paragraph
'          Capture 0: Instead,
'          Capture 1: it
'          Capture 2: is
'          Capture 3: a
'          Capture 4: nonsensical
'          Capture 5: paragraph
'       Group 2: paragraph
'          Capture 0: Instead
'          Capture 1: it
'          Capture 2: is
'          Capture 3: a
'          Capture 4: nonsensical
'          Capture 5: paragraph
'    
'    With explicit captures only:
'    The match: This is the first sentence.
'       Group 0: This is the first sentence.
'          Capture 0: This is the first sentence.
'    The match: Is it the beginning of a literary masterpiece?
'       Group 0: Is it the beginning of a literary masterpiece?
'          Capture 0: Is it the beginning of a literary masterpiece?
'    The match: I think not.
'       Group 0: I think not.
'          Capture 0: I think not.
'    The match: Instead, it is a nonsensical paragraph.
'       Group 0: Instead, it is a nonsensical paragraph.
'          Capture 0: Instead, it is a nonsensical paragraph.

Normal ifade deseni\b\(?((?>\w+),?\s?)+[\.!?]\)? aşağıdaki tabloda gösterildiği gibi tanımlanır.

Desen Açıklama
\b Sözcük sınırında başlayın.
\(? Açma parantezinin ("(") sıfır veya bir tekrarını eşleştirin.
(?>\w+),? Bir veya daha fazla sözcük karakterini, ardından sıfır veya bir virgülle eşleştirin. Sözcük karakterleri eşleştirirken geri dönmeyin.
\s? Sıfır veya bir beyaz boşluk karakterini eşleştirin.
((\w+),?\s?)+ Bir veya daha fazla sözcük karakteri, sıfır veya bir virgül ve sıfır veya bir boşluk karakterinin birleşimini bir veya daha fazla kez eşleştirin.
[\.!?]\)? Üç noktalama simgesinden herhangi birini eşleştirin, ardından sıfır veya bir kapama parantezi (").

Otomatik yakalamaları (?n) engellemek için satır içi öğesini de kullanabilirsiniz. Önceki normal ifade desenini, (?n) seçeneği yerine RegexOptions.ExplicitCapture satır içi öğesi kullanacak şekilde aşağıdaki örnek değiştirir.

using System;
using System.Text.RegularExpressions;

public class Explicit2Example
{
    public static void Main()
    {
        string input = "This is the first sentence. Is it the beginning " +
                       "of a literary masterpiece? I think not. Instead, " +
                       "it is a nonsensical paragraph.";
        string pattern = @"(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?";

        foreach (Match match in Regex.Matches(input, pattern))
        {
            Console.WriteLine($"The match: {match.Value}");
            int groupCtr = 0;
            foreach (Group group in match.Groups)
            {
                Console.WriteLine($"   Group {groupCtr}: {group.Value}");
                groupCtr++;
                int captureCtr = 0;
                foreach (Capture capture in group.Captures)
                {
                    Console.WriteLine($"      Capture {captureCtr}: {capture.Value}");
                    captureCtr++;
                }
            }
        }
    }
}
// The example displays the following output:
//       The match: This is the first sentence.
//          Group 0: This is the first sentence.
//             Capture 0: This is the first sentence.
//       The match: Is it the beginning of a literary masterpiece?
//          Group 0: Is it the beginning of a literary masterpiece?
//             Capture 0: Is it the beginning of a literary masterpiece?
//       The match: I think not.
//          Group 0: I think not.
//             Capture 0: I think not.
//       The match: Instead, it is a nonsensical paragraph.
//          Group 0: Instead, it is a nonsensical paragraph.
//             Capture 0: Instead, it is a nonsensical paragraph.
Imports System.Text.RegularExpressions

Module Explicit2Example
    Public Sub Main()
        Dim input As String = "This is the first sentence. Is it the beginning " +
                              "of a literary masterpiece? I think not. Instead, " +
                              "it is a nonsensical paragraph."
        Dim pattern As String = "(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?"

        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("The match: {0}", match.Value)
            Dim groupCtr As Integer = 0
            For Each group As Group In match.Groups
                Console.WriteLine("   Group {0}: {1}", groupCtr, group.Value)
                groupCtr += 1
                Dim captureCtr As Integer = 0
                For Each capture As Capture In group.Captures
                    Console.WriteLine("      Capture {0}: {1}", captureCtr, capture.Value)
                    captureCtr += 1
                Next
            Next
        Next
    End Sub
End Module
' The example displays the following output:
'       The match: This is the first sentence.
'          Group 0: This is the first sentence.
'             Capture 0: This is the first sentence.
'       The match: Is it the beginning of a literary masterpiece?
'          Group 0: Is it the beginning of a literary masterpiece?
'             Capture 0: Is it the beginning of a literary masterpiece?
'       The match: I think not.
'          Group 0: I think not.
'             Capture 0: I think not.
'       The match: Instead, it is a nonsensical paragraph.
'          Group 0: Instead, it is a nonsensical paragraph.
'             Capture 0: Instead, it is a nonsensical paragraph.

Son olarak, grup halinde otomatik yakalamaları engellemek için satır içi grup öğesini (?n:) kullanabilirsiniz. Aşağıdaki örnek, dış gruptaki ((?>\w+),?\s?)adsız yakalamaları engellemek için önceki deseni değiştirir. Bunun, iç gruptaki adsız yakalamaları da gizlediğini unutmayın.

using System;
using System.Text.RegularExpressions;

public class Explicit3Example
{
    public static void Main()
    {
        string input = "This is the first sentence. Is it the beginning " +
                       "of a literary masterpiece? I think not. Instead, " +
                       "it is a nonsensical paragraph.";
        string pattern = @"\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?";

        foreach (Match match in Regex.Matches(input, pattern))
        {
            Console.WriteLine($"The match: {match.Value}");
            int groupCtr = 0;
            foreach (Group group in match.Groups)
            {
                Console.WriteLine($"   Group {groupCtr}: {group.Value}");
                groupCtr++;
                int captureCtr = 0;
                foreach (Capture capture in group.Captures)
                {
                    Console.WriteLine($"      Capture {captureCtr}: {capture.Value}");
                    captureCtr++;
                }
            }
        }
    }
}
// The example displays the following output:
//       The match: This is the first sentence.
//          Group 0: This is the first sentence.
//             Capture 0: This is the first sentence.
//       The match: Is it the beginning of a literary masterpiece?
//          Group 0: Is it the beginning of a literary masterpiece?
//             Capture 0: Is it the beginning of a literary masterpiece?
//       The match: I think not.
//          Group 0: I think not.
//             Capture 0: I think not.
//       The match: Instead, it is a nonsensical paragraph.
//          Group 0: Instead, it is a nonsensical paragraph.
//             Capture 0: Instead, it is a nonsensical paragraph.
Imports System.Text.RegularExpressions

Module Explicit3Example
    Public Sub Main()
        Dim input As String = "This is the first sentence. Is it the beginning " +
                              "of a literary masterpiece? I think not. Instead, " +
                              "it is a nonsensical paragraph."
        Dim pattern As String = "\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?"

        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("The match: {0}", match.Value)
            Dim groupCtr As Integer = 0
            For Each group As Group In match.Groups
                Console.WriteLine("   Group {0}: {1}", groupCtr, group.Value)
                groupCtr += 1
                Dim captureCtr As Integer = 0
                For Each capture As Capture In group.Captures
                    Console.WriteLine("      Capture {0}: {1}", captureCtr, capture.Value)
                    captureCtr += 1
                Next
            Next
        Next
    End Sub
End Module
' The example displays the following output:
'       The match: This is the first sentence.
'          Group 0: This is the first sentence.
'             Capture 0: This is the first sentence.
'       The match: Is it the beginning of a literary masterpiece?
'          Group 0: Is it the beginning of a literary masterpiece?
'             Capture 0: Is it the beginning of a literary masterpiece?
'       The match: I think not.
'          Group 0: I think not.
'             Capture 0: I think not.
'       The match: Instead, it is a nonsensical paragraph.
'          Group 0: Instead, it is a nonsensical paragraph.
'             Capture 0: Instead, it is a nonsensical paragraph.

Derlenmiş normal ifadeler

Not

Mümkün olduğunda, seçeneğini kullanarak normal ifadeler derlemek yerine kaynak tarafından üretilen normal ifadeleri kullanın. Kaynak oluşturma, uygulamanızın daha hızlı başlatılmasına, daha hızlı çalışmasına ve kırpılabilir hale getirmenize yardımcı olabilir. Kaynak oluşturmanın ne zaman mümkün olduğunu öğrenmek için bkz Ne zaman kullanılır.

Varsayılan olarak, .NET'teki normal ifadeler yorumlanır. Bir Regex nesne örneği başlatıldığında veya statik Regex bir yöntem çağrıldığında, normal ifade deseni bir özel işlem kodları kümesine ayrıştırılır ve yorumlayıcı bu işlem kodlarını kullanarak normal ifadeyi çalıştırır. Bu bir dengeyi içerir: normal ifade altyapısını başlatma maliyeti çalışma zamanı performansı pahasına en aza indirilir.

seçeneğini kullanarak, yorumlanmış normal ifadeler yerine derlenmiş kullanabilirsiniz RegexOptions.Compiled . Bu durumda, bir kalıp normal ifade motoruna verildiğinde, bir opcode serisine ayrıştırılır ve ardından doğrudan ortak dil çalışma zamanına aktarılabilen ortak ara dile (CIL) dönüştürülür. Derlenmiş normal ifadeler, başlatma süresi pahasına çalışma zamanı performansını en üst düzeye çıkarır.

Not

Normal ifade yalnızca bir sınıf oluşturucusunun RegexOptions.Compiledoptions parametresine veya statik desen eşleştirme yöntemine Regex değer sağlanarak derlenebilir. Satır içi seçenek olarak kullanılamaz.

Hem statik hem de örnek normal ifadelerine yönelik çağrılarda derlenmiş normal ifadeleri kullanabilirsiniz. Statik normal ifadelerde, RegexOptions.Compiled seçeneği normal ifade desen eşleştirme yönteminin parametresine options geçirilir. Normal ifadeler örnek durumunda, sınıf oluşturucusunun options parametresine Regex aktarılır. Her iki durumda da performansın artırılmasına neden olur.

Ancak, performanstaki bu iyileştirme yalnızca aşağıdaki koşullar altında gerçekleşir:

  • Regex Belirli bir normal ifadeyi temsil eden bir nesne, normal ifade desen eşleştirme yöntemlerine yapılan birden çok çağrıda kullanılır.

  • Nesnenin Regex kapsam dışına çıkmalarına izin verilmiyor, bu nedenle yeniden kullanılabilir.

  • Statik normal ifade, normal ifade desen eşleştirme yöntemlerine yapılan birden çok çağrıda kullanılır. (Statik yöntem çağrılarında kullanılan normal ifadeler normal ifade altyapısı tarafından önbelleğe alındığından performans iyileştirmesi mümkündür.)

Not

seçeneği RegexOptions.Compiled , önceden tanımlanmış, derlenmiş normal ifadeler içeren özel amaçlı bir derleme oluşturan eski Regex.CompileToAssembly yöntemle ilgisizdir.

Beyaz boşluğu yoksay

Varsayılan olarak, normal ifade desenindeki boşluk önem taşır; normal ifade motorunu giriş dizesindeki bir beyaz boşluk karakteriyle eşleşmeye yönlendirir. Bu nedenle, "\b\w+\s" ve " " "\b\w+ normal ifadeleri kabaca eşdeğer normal ifadelerdir. Ek olarak, normal ifade deseninde sayı işareti (#) ile karşılaşıldığında, bu işaret eşleştirilecek bir değişmez karakter olarak yorumlanır.

seçeneği RegexOptions.IgnorePatternWhitespace veya x satır içi seçeneği, bu varsayılan davranışı aşağıdaki gibi değiştirir:

  • Normal ifade desenindeki boşaltılmamış boşluk yoksayılır. Normal ifade deseninin bir parçası olmak için boşluk karakterlerinin kaçış karakteri (örneğin, " veya \s "\ ") olması gerekir.

  • Sayı işareti (#), sabit bir karakter yerine bir açıklamanın başlangıcı olarak yorumlanır. Normal ifade desenindeki karakterden # sonraki \n karaktere veya dizenin sonuna kadar olan tüm metinler açıklama olarak yorumlanır.

Ancak, aşağıdaki durumlarda, RegexOptions.IgnorePatternWhitespace seçeneğini kullansanız bile, normal ifadedeki boşluk karakterleri yoksayılmaz.

  • Karakter sınıfı içindeki boşluklar her zaman tam anlamıyla yorumlanır. Örneğin, normal ifade deseni [ .,;:] herhangi bir tek boşluk karakteri, nokta, virgül, noktalı virgül veya iki nokta ile eşleşir.

  • Köşeli parantezli niceleyici içinde boşluklara izin verilmez, örneğin {n}, {n,}, ve {n,m}. Örneğin, normal ifade deseni \d{1, 3} boşluk karakteri içerdiğinden bir ile üç basamak arasındaki basamak dizileriyle eşleşemez.

  • Dil öğesinin tanıtımı sırasında karakter veya simge dizisinde boşluk olmasına izin verilmez. Örneğin:

    • Dil öğesi (?:alt ifadesi) , kapsüllenmeyen bir grubu temsil eder ve (?: öğenin bölümünde eklenmiş boşluk olamaz. Normal ifade motoru deseni ayrıştıramadığından ve ( ?:alt) ifadesi alt ifade ile eşleşmediğinden, (? :alt ifade) çalışma zamanında bir ArgumentException atar.

    • Unicode kategorisini veya adlandırılmış bloğu temsil eden dil öğesi \p{adı}, öğenin bölümüne eklenmiş boşluklar \p{ içeremez. Eğer bir boşluk eklerseniz, bu öğe çalışma zamanında bir ArgumentException fırlatır.

Bu seçeneğin etkinleştirilmesi, genellikle ayrıştırılması ve anlaşılması zor olan normal ifadeleri basitleştirmeye yardımcı olur. Okunabilirliği artırır ve normal ifadeyi belgelemesini mümkün kılar.

Aşağıdaki örnek aşağıdaki normal ifade desenini tanımlar:

\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.

Bu desen, yalnızca Explicit Captures Only bölümünde tanımlanan desene benzer, ancak RegexOptions.IgnorePatternWhitespace seçeneğini kullanarak desen boşluklarını yoksayar.

using System;
using System.Text.RegularExpressions;

public class Whitespace1Example
{
    public static void Main()
    {
        string input = "This is the first sentence. Is it the beginning " +
                       "of a literary masterpiece? I think not. Instead, " +
                       "it is a nonsensical paragraph.";
        string pattern = @"\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.";

        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnorePatternWhitespace))
            Console.WriteLine(match.Value);
    }
}
// The example displays the following output:
//       This is the first sentence.
//       Is it the beginning of a literary masterpiece?
//       I think not.
//       Instead, it is a nonsensical paragraph.
Imports System.Text.RegularExpressions

Module Whitespace1Example
    Public Sub Main()
        Dim input As String = "This is the first sentence. Is it the beginning " +
                              "of a literary masterpiece? I think not. Instead, " +
                              "it is a nonsensical paragraph."
        Dim pattern As String = "\b \(? ( (?>\w+) ,?\s? )+  [\.!?] \)? # Matches an entire sentence."

        For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnorePatternWhitespace)
            Console.WriteLine(match.Value)
        Next
    End Sub
End Module
' The example displays the following output:
'       This is the first sentence.
'       Is it the beginning of a literary masterpiece?
'       I think not.
'       Instead, it is a nonsensical paragraph.

Aşağıdaki örnek, desendeki boşlukları yoksaymak için satır içi seçenek (?x)'yı kullanır.

using System;
using System.Text.RegularExpressions;

public class Whitespace2Example
{
    public static void Main()
    {
        string input = "This is the first sentence. Is it the beginning " +
                       "of a literary masterpiece? I think not. Instead, " +
                       "it is a nonsensical paragraph.";
        string pattern = @"(?x)\b \(? ( (?>\w+) ,?\s? )+  [\.!?] \)? # Matches an entire sentence.";

        foreach (Match match in Regex.Matches(input, pattern))
            Console.WriteLine(match.Value);
    }
}
// The example displays the following output:
//       This is the first sentence.
//       Is it the beginning of a literary masterpiece?
//       I think not.
//       Instead, it is a nonsensical paragraph.
Imports System.Text.RegularExpressions

Module Whitespace2Example
    Public Sub Main()
        Dim input As String = "This is the first sentence. Is it the beginning " +
                              "of a literary masterpiece? I think not. Instead, " +
                              "it is a nonsensical paragraph."
        Dim pattern As String = "(?x)\b \(? ( (?>\w+) ,?\s? )+  [\.!?] \)? # Matches an entire sentence."

        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine(match.Value)
        Next
    End Sub
End Module
' The example displays the following output:
'       This is the first sentence.
'       Is it the beginning of a literary masterpiece?
'       I think not.
'       Instead, it is a nonsensical paragraph.

Sağdan sola modu

Varsayılan olarak, düzenli ifade motoru soldan sağa arar. seçeneğini kullanarak RegexOptions.RightToLeft arama yönünü tersine çevirebilirsiniz. Sağdan sola arama otomatik olarak dizenin son karakter konumunda başlar. gibi Regex.Match(String, Int32)bir başlangıç konumu parametresi içeren desen eşleştirme yöntemleri için, belirtilen başlangıç konumu, aramanın başlayacağı en sağdaki karakter konumunun dizinidir.

Not

Sağdan sola desen modu yalnızca bir RegexOptions.RightToLeft sınıf oluşturucusunun options parametresine veya statik desen eşleştirme yöntemine Regex değer sağlanarak kullanılabilir. Satır içi seçenek olarak kullanılamaz.

Örnek

Normal ifade \bb\w+\s , "b" harfiyle başlayan ve ardından boşluk karakteri gelen iki veya daha fazla karakter içeren sözcüklerle eşleşir. Aşağıdaki örnekte, giriş dizesi bir veya daha fazla "b" karakteri içeren üç sözcük içerir. birinci ve ikinci sözcükler "b" ile başlar ve üçüncü sözcük "b" ile biter. Sağdan sola arama örneğinden elde edilen çıktıda gösterildiği gibi, normal ifade deseniyle yalnızca birinci ve ikinci sözcükler eşleşir ve ikinci sözcük önce eşleştirilir.

using System;
using System.Text.RegularExpressions;

public class RTL1Example
{
    public static void Main()
    {
        string pattern = @"\bb\w+\s";
        string input = "build band tab";
        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.RightToLeft))
            Console.WriteLine($"'{match.Value}' found at position {match.Index}.");
    }
}
// The example displays the following output:
//       'band ' found at position 6.
//       'build ' found at position 0.
Imports System.Text.RegularExpressions

Module RTL1Example
    Public Sub Main()
        Dim pattern As String = "\bb\w+\s"
        Dim input As String = "build band tab"
        For Each match As Match In Regex.Matches(input, pattern, RegexOptions.RightToLeft)
            Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
        Next
    End Sub
End Module
' The example displays the following output:
'       'band ' found at position 6.
'       'build ' found at position 0.

Değerlendirme sırası

seçeneği RegexOptions.RightToLeft arama yönünü değiştirir ve ayrıca normal ifade deseninin değerlendirilme sırasını tersine çevirir. Sağdan sola aramada arama düzeni sağdan sola okunur. Yakalama grupları ve geri başvurular gibi öğeleri etkileyebildiği için bu ayrım önemlidir. Örneğin, ifade Regex.Match("abcabc", @"\1(abc)", RegexOptions.RightToLeft) bir eşleşme abcabcbulur, ancak soldan sağa aramada ()Regex.Match("abcabc", @"\1(abc)", RegexOptions.None) eşleşme bulunmaz. Bunun nedeni, bir eşleşmenin (abc) bulunması için numaralandırılmış yakalama grubu öğesinden (\1) önce öğesinin değerlendirilmesi gerekir.

Lookahead ve lookbehind ifadeleri

Bir lookahead ((?=subexpression)) veya lookbehind ((?<=subexpression)) onayı için eşleşmenin konumu sağdan sola aramada değişmez. İleriye bakan onaylar, geçerli eşleşme konumunun sağındaki kısmı kontrol eder; geriye bakan onaylar, geçerli eşleşme konumunun solundaki kısmı kontrol eder.

İpucu

Aramanın sağdan sola veya değil olmasına bakılmaksızın, lookbehind'ler geçerli eşleşme konumundan başlayarak sağdan sola arama kullanılarak uygulanır.

Örneğin, normal ifade (?<=\d{1,2}\s)\w+,\s\d{4} bir ay adından önceki bir tarihi test etmek için lookbehind onayını kullanır. Ardından normal ifade ay ve yıl ile eşleşir. Lookahead ve lookbehind ifadeleri hakkında bilgi için Gruplandırma Yapıları kısmına bakınız.

using System;
using System.Text.RegularExpressions;

public class RTL2Example
{
    public static void Main()
    {
        string[] inputs = { "1 May, 1917", "June 16, 2003" };
        string pattern = @"(?<=\d{1,2}\s)\w+,\s\d{4}";

        foreach (string input in inputs)
        {
            Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
            if (match.Success)
                Console.WriteLine($"The date occurs in {match.Value}.");
            else
                Console.WriteLine($"{input} does not match.");
        }
    }
}

// The example displays the following output:
//       The date occurs in May, 1917.
//       June 16, 2003 does not match.
Imports System.Text.RegularExpressions

Module RTL2Example
    Public Sub Main()
        Dim inputs() As String = {"1 May, 1917", "June 16, 2003"}
        Dim pattern As String = "(?<=\d{1,2}\s)\w+,\s\d{4}"

        For Each input As String In inputs
            Dim match As Match = Regex.Match(input, pattern, RegexOptions.RightToLeft)
            If match.Success Then
                Console.WriteLine("The date occurs in {0}.", match.Value)
            Else
                Console.WriteLine("{0} does not match.", input)
            End If
        Next
    End Sub
End Module

' The example displays the following output:
'       The date occurs in May, 1917.
'       June 16, 2003 does not match.

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

Desen Açıklama
(?<=\d{1,2}\s) Eşleşmenin başında bir veya iki ondalık basamak ve ardından boşluk olmalıdır.
\w+ Bir veya daha fazla sözcük karakteri eşleştir.
, Bir virgül karakteri eşleştirin.
\s Bir boşluk karakteri ile eşleştirin.
\d{4} Dört ondalık basamağı eşleştirin.

ECMAScript eşleştirme davranışı

Varsayılan olarak, normal ifade altyapısı normal ifade desenini metin girişiyle eşleştirirken kurallı davranış kullanır. Ancak, RegexOptions.ECMAScript seçeneğini belirterek normal ifade yürütme altyapısına ECMAScript eşleştirme davranışını kullanacak şekilde yönlendirebilirsiniz.

Not

ECMAScript'e uygun davranış, yalnızca RegexOptions.ECMAScript değerini bir options sınıfı oluşturucusunun veya statik desen eşleştirme yönteminin Regex parametresine sağlayarak mümkündür. Satır içi seçenek olarak kullanılamaz.

Bu RegexOptions.ECMAScript seçenek yalnızca , RegexOptions.IgnoreCaseve RegexOptions.Multiline seçenekleriyle RegexOptions.Compiledbirleştirilebilir. Normal ifadede başka bir seçeneğin kullanılması sonucunda bir ArgumentOutOfRangeExceptionolur.

ECMAScript ve kurallı normal ifadelerin davranışı üç alanda farklılık gösterir: karakter sınıfı söz dizimi, kendi kendine başvuran yakalama grupları ve sekizli ve geri başvuru yorumu.

  • Karakter sınıfı söz dizimi. Kurallı normal ifadeler Unicode'u desteklediği halde ECMAScript desteklemediğinden, ECMAScript'teki karakter sınıflarının söz dizimi daha sınırlıdır ve bazı karakter sınıfı dil öğeleri farklı anlamlara sahiptir. Örneğin, ECMAScript Unicode kategorisi veya blok öğeleri \p ve \P gibi dil öğelerini desteklemez. Benzer şekilde, bir sözcük karakteriyle eşleşen \w öğesi, ECMAScript kullanılırken [a-zA-Z_0-9] karakter sınıfına ve kurallı davranış kullanılırken [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] karakter sınıfına eşdeğerdir. Daha fazla bilgi için bkz . Karakter Sınıfları.

    Aşağıdaki örnekte kurallı ve ECMAScript desen eşleştirme arasındaki fark gösterilmektedir. Ardından boşluk karakterleri gelen sözcüklerle eşleşen bir normal ifade \b(\w+\s*)+tanımlar. Giriş, biri Latin karakter kümesini, diğeri kiril karakter kümesini kullanan iki dizeden oluşur. Çıktıda gösterildiği gibi ECMAScript eşleştirmesi Regex.IsMatch(String, String, RegexOptions) kullanan yöntemine yapılan çağrı Kiril sözcüklerle eşleşemezken kurallı eşleştirme kullanan yöntem çağrısı bu sözcüklerle eşleşir.

    using System;
    using System.Text.RegularExpressions;
    
    public class EcmaScriptExample
    {
        public static void Main()
        {
            string[] values = { "целый мир", "the whole world" };
            string pattern = @"\b(\w+\s*)+";
            foreach (var value in values)
            {
                Console.Write("Canonical matching: ");
                if (Regex.IsMatch(value, pattern))
                    Console.WriteLine($"'{value}' matches the pattern.");
                else
                    Console.WriteLine($"{value} does not match the pattern.");
    
                Console.Write("ECMAScript matching: ");
                if (Regex.IsMatch(value, pattern, RegexOptions.ECMAScript))
                    Console.WriteLine($"'{value}' matches the pattern.");
                else
                    Console.WriteLine($"{value} does not match the pattern.");
                Console.WriteLine();
            }
        }
    }
    // The example displays the following output:
    //       Canonical matching: 'целый мир' matches the pattern.
    //       ECMAScript matching: целый мир does not match the pattern.
    //
    //       Canonical matching: 'the whole world' matches the pattern.
    //       ECMAScript matching: 'the whole world' matches the pattern.
    
    Imports System.Text.RegularExpressions
    
    Module Ecma1Example
        Public Sub Main()
            Dim values() As String = {"целый мир", "the whole world"}
            Dim pattern As String = "\b(\w+\s*)+"
            For Each value In values
                Console.Write("Canonical matching: ")
                If Regex.IsMatch(value, pattern) Then
                    Console.WriteLine("'{0}' matches the pattern.", value)
                Else
                    Console.WriteLine("{0} does not match the pattern.", value)
                End If
    
                Console.Write("ECMAScript matching: ")
                If Regex.IsMatch(value, pattern, RegexOptions.ECMAScript) Then
                    Console.WriteLine("'{0}' matches the pattern.", value)
                Else
                    Console.WriteLine("{0} does not match the pattern.", value)
                End If
                Console.WriteLine()
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       Canonical matching: 'целый мир' matches the pattern.
    '       ECMAScript matching: целый мир does not match the pattern.
    '       
    '       Canonical matching: 'the whole world' matches the pattern.
    '       ECMAScript matching: 'the whole world' matches the pattern.
    
  • Kendi kendine başvuran yakalama grupları. Kendisine bir geri başvuru içeren normal ifade yakalama sınıfı, her yakalama yinelemesiyle güncelleştirilmelidir. Aşağıdaki örnekte gösterildiği gibi bu özellik, normal ifadenin ((a+)(\1) ?)+ ECMAScript kullanırken " aa aa aaaaaa " giriş dizesiyle eşleşmesini sağlar, ancak kurallı eşleştirme kullanılırken eşleşmez.

    using System;
    using System.Text.RegularExpressions;
    
    public class EcmaScript2Example
    {
        static string pattern;
    
        public static void Main()
        {
            string input = "aa aaaa aaaaaa ";
            pattern = @"((a+)(\1) ?)+";
    
            // Match input using canonical matching.
            AnalyzeMatch(Regex.Match(input, pattern));
    
            // Match input using ECMAScript.
            AnalyzeMatch(Regex.Match(input, pattern, RegexOptions.ECMAScript));
        }
    
        private static void AnalyzeMatch(Match m)
        {
            if (m.Success)
            {
                Console.WriteLine($"'{pattern}' matches {m.Value} at position {m.Index}.");
                int grpCtr = 0;
                foreach (Group grp in m.Groups)
                {
                    Console.WriteLine($"   {grpCtr}: '{grp.Value}'");
                    grpCtr++;
                    int capCtr = 0;
                    foreach (Capture cap in grp.Captures)
                    {
                        Console.WriteLine($"      {capCtr}: '{cap.Value}'");
                        capCtr++;
                    }
                }
            }
            else
            {
                Console.WriteLine("No match found.");
            }
            Console.WriteLine();
        }
    }
    // The example displays the following output:
    //    No match found.
    //
    //    '((a+)(\1) ?)+' matches aa aaaa aaaaaa  at position 0.
    //       0: 'aa aaaa aaaaaa '
    //          0: 'aa aaaa aaaaaa '
    //       1: 'aaaaaa '
    //          0: 'aa '
    //          1: 'aaaa '
    //          2: 'aaaaaa '
    //       2: 'aa'
    //          0: 'aa'
    //          1: 'aa'
    //          2: 'aa'
    //       3: 'aaaa '
    //          0: ''
    //          1: 'aa '
    //          2: 'aaaa '
    
    Imports System.Text.RegularExpressions
    
    Module Ecma2Example
        Dim pattern As String
    
        Public Sub Main()
            Dim input As String = "aa aaaa aaaaaa "
            pattern = "((a+)(\1) ?)+"
    
            ' Match input using canonical matching.
            AnalyzeMatch(Regex.Match(input, pattern))
    
            ' Match input using ECMAScript.
            AnalyzeMatch(Regex.Match(input, pattern, RegexOptions.ECMAScript))
        End Sub
    
        Private Sub AnalyzeMatch(m As Match)
            If m.Success Then
                Console.WriteLine("'{0}' matches {1} at position {2}.",
                                  pattern, m.Value, m.Index)
                Dim grpCtr As Integer = 0
                For Each grp As Group In m.Groups
                    Console.WriteLine("   {0}: '{1}'", grpCtr, grp.Value)
                    grpCtr += 1
                    Dim capCtr As Integer = 0
                    For Each cap As Capture In grp.Captures
                        Console.WriteLine("      {0}: '{1}'", capCtr, cap.Value)
                        capCtr += 1
                    Next
                Next
            Else
                Console.WriteLine("No match found.")
            End If
            Console.WriteLine()
        End Sub
    End Module
    ' The example displays the following output:
    '    No match found.
    '    
    '    '((a+)(\1) ?)+' matches aa aaaa aaaaaa  at position 0.
    '       0: 'aa aaaa aaaaaa '
    '          0: 'aa aaaa aaaaaa '
    '       1: 'aaaaaa '
    '          0: 'aa '
    '          1: 'aaaa '
    '          2: 'aaaaaa '
    '       2: 'aa'
    '          0: 'aa'
    '          1: 'aa'
    '          2: 'aa'
    '       3: 'aaaa '
    '          0: ''
    '          1: 'aa '
    '          2: 'aaaa '
    

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

    Desen Açıklama
    (a+) "a" harfini bir veya daha fazla kez eşleştirin. Bu ikinci yakalama grubudur.
    (\1) Birinci yakalama grubunun yakaladığı alt dizeyi eşleştirin. Bu, üçüncü yakalama grubudur.
    ? Sıfır veya bir boşluk karakteri eşleştirin.
    ((a+)(\1) ?)+ Bir veya daha fazla "a" karakterinin desenini ve ardından ilk yakalama grubuyla eşleşen bir dizeyi ve ardından sıfır veya bir boşluk karakterini bir veya daha fazla kez eşleştirin. İlk yakalama grubu budur.
  • Sekizli kaçışlar ile arka başvurular arasındaki belirsizliklerin çözülmesi. Aşağıdaki tabloda kanonik ve ECMAScript normal ifadelerine göre sekizlik ve geri başvuru yorumlaması arasındaki farklar özetlenir.

    Düzenli ifade Kurallı davranış ECMAScript davranışı
    \0 ardından 0 ile 2 sekizlik rakamlar Sekizli sayı olarak yorumla. Örneğin, \044 her zaman sekizlik değer olarak yorumlanır ve "$" anlamına gelir. Aynı davranış.
    \ ardından 1 ile 9 arasında bir rakam gelir ve ek ondalık basamak bulunmaz, Geri başvuru olarak yorumla. Örneğin, \9 dokuzuncu bir yakalama grubu olmasa bile her zaman dokuzuncu bir geri başvuruyu ifade eder. Yakalama grubu yoksa, normal ifade ayrıştırıcısı ArgumentException hatasını oluşturur. Tek bir ondalık basamak yakalama grubu varsa, o rakama geri dönün. Aksi takdirde, değeri literal değer olarak yorumlayın.
    \ ardından 1 ile 9 arasından bir basamak ve ardından ek ondalık basamaklar Rakamları ondalık değer olarak yorumlayın. Eğer bu yakalama grubu mevcutsa, ifadeyi geri başvuru olarak yorumla.

    Aksi takdirde, baştaki sekizli rakamları sekizlik 377'ye kadar yorumlayın; yani, değerin en düşük 8 bitini dikkate alın. Geriye kalan basamakları harfi olarak yorumla. Örneğin, ifadesinde \3000, 300 numaralı grup varsa geriye başvuru 300 olarak yorumla; 300 numaralı grup yoksa, sekizli 300 sonrasında gelen 0 olarak yorumla.
    Mümkün olduğunca çok basamağı, bir yakalamaya referans verebilecek ondalık bir değere dönüştürerek geri başvuru olarak yorumlayın. Hiçbir basamak dönüştürülemiyorsa, baştaki sekizlik basamakları sekizli olarak, 377'ye kadar yorumlayın; kalan basamakları ise harfiyen alın.

Sabit kültürü kullanarak karşılaştırma

Varsayılan olarak, normal ifade altyapısı büyük/küçük harfe duyarsız karşılaştırmalar gerçekleştirdiğinde, eşdeğer büyük ve küçük harf karakterlerini belirlemek için geçerli kültürün büyük/küçük harf kurallarını kullanır.

Ancak bu davranış, özellikle kullanıcı girişini parolalar, dosyalar veya URL'ler gibi sistem kaynaklarının adlarıyla karşılaştırırken bazı karşılaştırma türleri için istenmeyen bir davranıştır. Aşağıdaki örnekte bu tür bir senaryo gösterilmektedir. Kod, URL'si FILE:// ile önceden oluşturulmuş herhangi bir kaynağa erişimi engellemeye yöneliktir. Normal ifade, $FILE:// kullanarak dize üzerinde büyük/küçük harf duyarsız bir eşleşme dener. Ancak mevcut sistem kültürü tr-TR (Türk-Türkiye) olduğunda "i" büyük harfle eşdeğer değildir. Sonuç olarak, Regex.IsMatch yöntemine yapılan çağrı false döndürür ve dosyaya erişime izin verilir.

CultureInfo defaultCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");

string input = "file://c:/Documents.MyReport.doc";
string pattern = "FILE://";

Console.WriteLine($"Culture-sensitive matching ({Thread.CurrentThread.CurrentCulture.Name} culture)...");
if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
    Console.WriteLine("URLs that access files are not allowed.");
else
    Console.WriteLine($"Access to {input} is allowed.");

Thread.CurrentThread.CurrentCulture = defaultCulture;
// The example displays the following output:
//       Culture-sensitive matching (tr-TR culture)...
//       Access to file://c:/Documents.MyReport.doc is allowed.
Dim defaultCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
Thread.CurrentThread.CurrentCulture = New CultureInfo("tr-TR")

Dim input As String = "file://c:/Documents.MyReport.doc"
Dim pattern As String = "$FILE://"

Console.WriteLine("Culture-sensitive matching ({0} culture)...",
                  Thread.CurrentThread.CurrentCulture.Name)
If Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase) Then
    Console.WriteLine("URLs that access files are not allowed.")
Else
    Console.WriteLine("Access to {0} is allowed.", input)
End If

Thread.CurrentThread.CurrentCulture = defaultCulture
' The example displays the following output:
'       Culture-sensitive matching (tr-TR culture)...
'       Access to file://c:/Documents.MyReport.doc is allowed.

Not

Büyük/küçük harfe duyarlı olan ve sabit kültürü kullanan dize karşılaştırmaları hakkında daha fazla bilgi için bkz . Dizeleri Kullanmak için En İyi Yöntemler.

Geçerli kültürün büyük/küçük harfe duyarsız karşılaştırmalarını kullanmak yerine, dildeki kültürel farklılıkları yoksaymak ve değişmez kültürün kurallarını kullanmak için RegexOptions.CultureInvariant seçeneğini belirtebilirsiniz.

Not

Değişmez kültürü kullanarak karşılaştırma yalnızca RegexOptions.CultureInvariant değerinin sınıf oluşturucusu veya statik desen eşleştirme yönteminin options parametresine sağlanmasıyla Regex kullanılabilir. Satır içi seçenek olarak kullanılamaz.

Aşağıdaki örnek, statik Regex.IsMatch(String, String, RegexOptions) yöntemi içeren seçeneklerle RegexOptions.CultureInvariantçağrılmaları dışında önceki örnekle aynıdır. Geçerli kültür Türkçe (Türkiye) olarak ayarlandığında bile normal ifade altyapısı "DOSYA" ve "dosya" ile başarıyla eşleşip dosya kaynağına erişimi engelleyebilir.

CultureInfo defaultCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");

string input = "file://c:/Documents.MyReport.doc";
string pattern = "FILE://";

Console.WriteLine("Culture-insensitive matching...");
if (Regex.IsMatch(input, pattern,
                  RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
    Console.WriteLine("URLs that access files are not allowed.");
else
    Console.WriteLine($"Access to {input} is allowed.");

Thread.CurrentThread.CurrentCulture = defaultCulture;
// The example displays the following output:
//       Culture-insensitive matching...
//       URLs that access files are not allowed.
Dim defaultCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
Thread.CurrentThread.CurrentCulture = New CultureInfo("tr-TR")

Dim input As String = "file://c:/Documents.MyReport.doc"
Dim pattern As String = "$FILE://"

Console.WriteLine("Culture-insensitive matching...")
If Regex.IsMatch(input, pattern,
               RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant) Then
    Console.WriteLine("URLs that access files are not allowed.")
Else
    Console.WriteLine("Access to {0} is allowed.", input)
End If
Thread.CurrentThread.CurrentCulture = defaultCulture
' The example displays the following output:
'        Culture-insensitive matching...
'        URLs that access files are not allowed.

Geri izleme yapmadan modu

Varsayılan olarak, . NET'in regex altyapısı, desen eşleşmelerini bulmaya çalışmak için geri izlemeyi kullanır. Geri izleme altyapısı, tek bir desenle eşleşmeye çalışan altyapıdır ve bu başarısız olursa geri gider ve alternatif bir desenle eşleştirmeye çalışır, vb. Geri izleme altyapısı tipik durumlar için çok hızlıdır, ancak desen değişimlerinin sayısı arttıkça yavaşlar ve bu da yıkıcı geri dönüşlere yol açabilir. RegexOptions.NonBacktracking.NET 7'de sunulan seçenek geri izleme kullanmaz ve en kötü senaryoyu önler. Amacı, aranan girişe bakılmaksızın tutarlı bir şekilde iyi davranış sağlamaktır.

Bu RegexOptions.NonBacktracking seçenek, diğer yerleşik altyapıların desteklediği her şeyi desteklemez. Seçenek, RegexOptions.RightToLeft ile RegexOptions.ECMAScript özellikle birlikte kullanılamaz. Ayrıca, desende aşağıdaki yapılara izin vermez:

  • Atomik gruplar
  • Arka Referanslar
  • Dengeleme grupları
  • Koşullar
  • Aramalar
  • Başlangıç tutturucuları (\G)

RegexOptions.NonBacktracking ayrıca yürütmeyle ilgili olarak küçük bir fark gösterir. Yakalama grubu bir döngüdeyse, çoğu (non-.NET) regex altyapısı yalnızca bu yakalama için son eşleşen değeri sağlar. Fakat. NET'in regex altyapısı bir döngü içinde yakalanan tüm değerleri izler ve bunlara erişim sağlar. Seçeneği RegexOptions.NonBacktracking diğer çoğu regex uygulamasına benzer ve yalnızca son yakalamayı sağlamayı destekler.

Daha fazla bilgi için Düzenli ifadelerde geri izleme'ye bakın.

Ayrıca bkz.