Normal İfade Seçenekleri
Varsayılan olarak, bir giriş dizesinin normal ifade desendeki herhangi bir değişmez karakterle karşılaştırılması büyük/küçük harfe duyarlıdır, normal ifade desendeki boşluk değişmez boşluk karakterleri olarak yorumlanır ve normal ifadedeki yakalama grupları örtük olarak ve açıkça olarak adlandırılmıştı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çenekler, normal ifade deseninin bir parçası olarak satır içi olarak dahil edilebilir veya bir sınıf oluşturucu ya da statik desen eşleştirme yöntemine sabit liste değeri System.Text.RegularExpressions.Regex System.Text.RegularExpressions.RegexOptions olarak sağlanmalıdır.
| RegexOptions üyesi | Satır içi karakter | Etki |
|---|---|---|
| None | Kullanılamaz | Varsayılan davranışı kullanın. Daha fazla bilgi için bkz. Varsayılan Seçenekler. |
| IgnoreCase | i |
Büyük küçük harf duyarlı eşleme kullanın. Daha fazla bilgi için bkz. Büyük/Büyük/Büyük Harfe Duyarsız Eşleştirme. |
| Multiline | m |
Her satırın başında ve sonunda (giriş dizesinin başlangıcı ve sonu yerine) ve eşleşmesi ^ $ için çok satırlı modu kullanın. Daha fazla bilgi için bkz. Çok Satırlı Mod. |
| Singleline | s |
Noktanın (.) her karakterle (hariç her karakter yerine) eş olduğu tek satırlı modu \n kullanın. Daha fazla bilgi için bkz. Tek Satırlı Mod. |
| ExplicitCapture | n |
Adsız grupları yakalamayın. Yalnızca geçerli yakalamalar form adı alt ifadesinde açıkça veya (?< numaralandı > grupları olarak adlandırılmıştır. ) Daha fazla bilgi için bkz. Yalnızca Açık Yakalamalar. |
| Compiled | Kullanılamaz | Normal ifadeyi bir derlemeye derle. Daha fazla bilgi için bkz. Derlenmiş Normal İfadeler. |
| IgnorePatternWhitespace | x |
Düzenden dışlanmamış boşluğu dışlama ve sayı işaretinden sonra yorumları etkinleştirme ( # ). Daha fazla bilgi için bkz. Boşluğu Yoksayma. |
| RightToLeft | Kullanılamaz | Arama yönünü değiştirme. Arama, soldan sağa değil, sağdan sola doğru taşınır. Daha fazla bilgi için bkz. Sağdan Sola Modu. |
| ECMAScript | Kullanılamaz | İfade için ECMAScript uyumlu davranışı etkinleştirin. Daha fazla bilgi için bkz. ECMAScript Eşleştirme Davranışı. |
| CultureInvariant | Kullanılamaz | Dille ilgili kültürel farkları yoksayın. Daha fazla bilgi için bkz. Sabit Kültür Kullanarak Karşılaştırma. |
Seçenekleri Belirtme
Normal ifadeler için seçenekleri üç şekilde belirtebilirsiniz:
Veya
optionsgibi bir System.Text.RegularExpressions.Regex sınıf oluşturucusu veya statikShared(Visual Basic) desen eşleştirme yönteminin Regex(String, RegexOptions) Regex.Match(String, String, RegexOptions) parametresinde. parametresi,optionsnumaralandırmış değerlerin bitwise OR System.Text.RegularExpressions.RegexOptions birleşimidir.Bir sınıf oluşturucusuz parametresi kullanılarak bir örneğine seçenekler Regex
optionssağlanmalıdır, seçenekler özelliğine System.Text.RegularExpressions.RegexOptions atanır. Ancak, System.Text.RegularExpressions.RegexOptions özelliği normal ifade deseninin kendisinde satır içi seçenekleri yansıtmaz.Aşağıdaki örnek, bir gösterim sağlar. Metodun parametresini kullanarak büyük/büyük/büyük harfe duyarsız eşleştirmeyi etkinleştirir ve "d" harfiyle başlayan sözcükleri belirtirken desen boşluklarını
optionsRegex.Match(String, String, RegexOptions) yoksayar.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("'{0}// found at index {1}.", match.Value, 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 ile bir normal ifade düzeninde satır içi seçenekleri
(?imnsx-imnsx)uygulayarak. Seçenek, seçeneğin desenin sonuna veya seçeneğin başka bir satır içi seçenek tarafından tanımlanmamış olduğu noktaya kadar tanımlanan noktadan desene uygulanır. Bir örneğin System.Text.RegularExpressions.RegexOptions özelliğinin bu Regex satır içi seçenekleri yansıtmadığını unutmayın. Daha fazla bilgi için Çeşitli Yapılar konu başlığına bakın.Aşağıdaki örnek, bir gösterim sağlar. Satır içi seçenekleri, büyük/büyük/büyük harfe duyarsız eşleştirmeyi etkinleştirmek ve "d" harfiyle başlayan sözcükleri tanımlamada desen boşluklarını yoksaymak için kullanır.
string pattern = @"(?ix) d \w+ \s"; string input = "Dogs are decidedly good pets."; foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine("'{0}// found at index {1}.", match.Value, 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.Söz dizimi alt ifadesi ile bir normal ifade düzeninde belirli bir gruplama yapısında
(?imnsx-imnsx:satır içi seçenekleri uygulayarak.)Bir seçenek kümesi, kümeyi açmadan önce işaret yok; bir seçenek kümesi kapatmadan önce eksi işareti. (?dil yapısı söz dizimlerinin seçeneklerin etkin veya devre dışı olması gerekip gerek yoktur sabit bir kısmıdır.) Seçenek yalnızca bu grup için geçerlidir. Daha fazla bilgi için bkz. Yapıları Gruplama.Aşağıdaki örnek, bir gösterim sağlar. Bir gruplama yapısında satır içi seçenekleri, büyük/küçük harfe duyarsız eşleştirmeyi etkinleştirmek ve "d" harfiyle başlayan sözcükleri tanımlamada desen boşluklarını yoksaymak için 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("'{0}// found at index {1}.", match.Value, 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ümesi öncesinde eksi işareti ( - ) bu seçenekleri devre dışıdır. Örneğin, satır içi yapısı (?ix-ms) ve RegexOptions.IgnoreCase RegexOptions.IgnorePatternWhitespace seçeneklerini, ve seçeneklerini RegexOptions.Multiline RegexOptions.Singleline de kapatıyor. Tüm normal ifade seçenekleri varsayılan olarak kapalıdır.
Not
Bir oluşturucu veya yöntem çağrısının parametresinde belirtilen normal ifade seçenekleri, normal ifade düzeninde satır içinde belirtilen seçeneklerle çakışıyorsa, options satır içi seçenekler kullanılır.
Aşağıdaki beş normal ifade seçeneği hem options parametresiyle hem de satır içi olarak ayar olabilir:
Aşağıdaki beş normal ifade seçeneği parametresi kullanılarak options ya da satır içi olarak ayar kullanılamaz:
Seçenekleri Belirleme
Salt okunur özelliğin değerini alarak, bir nesneye örneği anında hangi seçeneklerin Regex sağlandı olduğunu Regex.Options anabilirsiniz. Bu özellik özellikle yöntemi tarafından oluşturulan derlenmiş bir normal ifade için tanımlanan seçenekleri belirlemek için Regex.CompileToAssembly yararlıdır.
dışında herhangi bir seçeneğin varlığını test etmek için, özelliğinin değeri ve ilgilendiğiniz değer ile RegexOptions.None bir AND Regex.Options işlemi RegexOptions gerçekleştirin. Ardından sonucun bu değere eşit olup olmadığını RegexOptions test etmek. Aşağıdaki örnek seçeneğin ayar olup RegexOptions.IgnoreCase olmadığını test ediyor.
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
için test RegexOptions.None etmek için, aşağıdaki örnekte gösterildiği Regex.Options gibi özelliğinin RegexOptions.None değerinin değerine eşit olup olmadığını belirler.
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 listelanmaktadır.
Varsayılan Seçenekler
RegexOptions.Noneseçeneği, hiçbir seçenek belirtilmemiş olduğunu ve normal ifade altyapısının varsayılan davranışını kullandığını gösterir. Bu, aşağıdakileri içerir:
Desen, ECMAScript normal ifadesi yerine kurallı olarak yorumlanır.
Normal ifade deseni, giriş dizesinde soldan sağa eştir.
Karşılaştırmalar büyük/büyük/büyük harfe duyarlıdır.
ve
^dili$öğeleri, giriş dizesinin başlangıcı ve sonuyla eştir. Giriş dizesinin sonu, sonda bir yeni satır karakteri\nolabilir.dil
.öğesi dışında her karakterle eşler.\nNormal ifade desendeki tüm boşluklar değişmez boşluk karakteri olarak yorumlanır.
Geçerli kültürün kuralları, deseni giriş dizesiyle karşılaştırırken kullanılır.
Normal ifade desenlerinde grupları yakalamak hem örtülü hem de açıktır.
Not
Seçeneğin RegexOptions.None satır içi eşdeğeri yoktur. Normal ifade seçenekleri satır içi uygulandığında, varsayılan davranış belirli bir seçenek kapatarak seçenek temelinde geri yüklenir. Örneğin, (?i) büyük/büyük/büyük harfe duyarsız karşılaştırmayı ve varsayılan (?-i) büyük/büyük/büyük harfe duyarlı karşılaştırmayı geri yüklemesini sağlar.
seçeneği RegexOptions.None normal ifade altyapısının varsayılan davranışını temsil ettiği için, bir yöntem çağrısında nadiren belirtilir. Bunun yerine parametresi olmayan bir oluşturucu veya statik desen options eşleştirme yöntemi çağrılır.
Case-Insensitive Eşleştirme
seçeneği IgnoreCase veya satır içi i seçeneği, büyük/alta duyarlı olmayan eşleştirme sağlar. Varsayılan olarak, geçerli kültürün büyük/yeni kuralları kullanılır.
Aşağıdaki örnek, "the" ile başlayan \bthe\w*\b tüm sözcüklerle eşleşen bir normal ifade deseni tanımlar. yöntemine yapılan ilk çağrı varsayılan büyük/büyük/büyük harfe duyarlı karşılaştırmayı kullandığı için çıkış, cümleyi başlayan Match "The" dizesinin eşleşmez olduğunu gösterir. yöntemi olarak ayarlanmış Match seçeneklerle çağrıldısında bu eşlenir. IgnoreCase
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 {0} at index {1}.", match.Value, match.Index);
Console.WriteLine();
foreach (Match match in Regex.Matches(input, pattern,
RegexOptions.IgnoreCase))
Console.WriteLine("Found {0} at index {1}.", match.Value, 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, büyük/büyük/büyük/büyük harfe duyarsız karşılaştırma sağlamak için parametresi yerine satır içi seçenekleri kullanmak için önceki örnekteki normal options ifade desenini değiştiriyor. İlk desen, yalnızca "the" dizesinde "t" harfine uygulanan bir gruplama yapısında büyük/küçük harfe duyarlı olmayan seçeneği tanımlar. Seçenek yapısı desenin başında oluştuğu için ikinci desen, normal ifadenin tamamına büyük/harfe duyarlı olmayan seçeneği uygular.
using System;
using System.Text.RegularExpressions;
public class Example
{
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 {0} at index {1}.", match.Value, match.Index);
Console.WriteLine();
pattern = @"(?i)\bthe\w*\b";
foreach (Match match in Regex.Matches(input, pattern,
RegexOptions.IgnoreCase))
Console.WriteLine("Found {0} at index {1}.", match.Value, 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 Example
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
seçeneği veya satır içi seçeneği, normal ifade altyapısının birden çok RegexOptions.Multiline m satırdan oluşan bir giriş dizesini işlemesini sağlar. Ve dili öğelerinin yorumunu, giriş dizesinin başlangıcı ve sonu yerine bir satırın başlangıcı ve sonuyla ^ $ eş olacak şekilde değiştirir.
Varsayılan olarak, $ giriş dizesinin yalnızca sonuyla eşler. seçeneğini RegexOptions.Multiline belirtirseniz, yeni satır karakteri ( ) veya \n giriş dizesinin sonuyla eşler. Ancak satır başı/satır besleme karakteri birleşimiyle eşleşmez. Bunları başarıyla eşleşmek için yalnızca yerine alt \r?$ ifadeyi $ kullanın.
Aşağıdaki örnek, atıcıların adlarını ve puanlarını ayıklar ve bunları azalan SortedList<TKey,TValue> düzende sıralanan bir koleksiyona ekler. yöntemi Matches iki kez çağrılır. İlk yöntem çağrısında normal ifade şeklindedir ^(\w+)\s(\d+)$ ve hiçbir seçenek ayar değildir. Çıkışta da olduğu gibi, normal ifade altyapısı giriş dizesinin başlangıcı ve bitişi ile birlikte giriş deseniyle eşleyemeyeyr, hiçbir eşleşme bulunamadı. İkinci yöntem çağrısında, normal ifade olarak değiştirilir ^(\w+)\s(\d+)\r?$ ve seçenekler olarak RegexOptions.Multiline ayarlanır. Çıkışta da olduğu gibi, adlar ve puanlar başarıyla eşlendi ve puanlar azalan düzende görüntülenir.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Example
{
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 = @"^(\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("{0}: {1}", 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:
// 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 Example
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 = "^(\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 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:
' 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 | Description |
|---|---|
^ |
Satırın başından başlar. |
(\w+) |
Bir veya daha fazla sözcük karakteri eşleştir. Bu ilk yakalama grubudur. |
\s |
Bir boşluk karakteri ile eşleştirin. |
(\d+) |
Bir veya daha fazla ondalık basamağı eşleştirin. Bu ikinci yakalama grubudur. |
\r? |
Sıfır veya bir satır başı karakterini eşler. |
$ |
Satırın sonunda sona erer. |
Aşağıdaki örnek, çok satırlı seçeneği ayarlamak için satır içi seçeneğini kullanması dışında (?m) öncekine eşdeğerdir.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Example
{
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("{0}: {1}", 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 Example
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
seçeneği veya satır içi seçeneği, normal ifade altyapısının giriş dizesini tek bir satırdan oluşan bir dize RegexOptions.Singleline s gibi davranmasına neden olur. Bunu, yeni satır karakteri veya dışında her karakterle eşleştirmek yerine her karakterle eş olacak şekilde nokta ( ) dil . öğesinin davranışını değiştirerek \n \u000A yapar.
Dil $ öğesi dizenin sonuyla veya sonundaki yeni satır karakteriyle eşler. \n
Aşağıdaki örnek, seçeneğini kullanarak dil . öğesinin davranışının nasıl değişti olduğunu RegexOptions.Singleline göstermektedir. Normal ifade ^.+ dizenin başında başlar ve her karakterle eşler. Varsayılan olarak, eşleşme ilk satırın sonunda sona erer; normal ifade deseni satır başı karakteriyle veya \r \u000D ile eştir, ancak ile \n eşleşmez. seçeneği giriş dizesinin tamamını tek bir satır olarak yorumlasa da, giriş dizesinde yer alan her RegexOptions.Singleline karakterle (dahil) \n eşler.
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ırlı modu etkinleştirmek için satır içi seçeneğini kullanması dışında (?s) öncekine eşdeğerdir.
using System;
using System.Text.RegularExpressions;
public class Example
{
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 Example
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 desende parantez kullanımıyla tanımlanır. Adlandırılmış gruplara ad alt ifade dili seçeneğiyle bir ad veya sayı (?< > ) atanırken, adsız gruplara dizin tarafından erişilebilir. GroupCollectionnesnesinde, adsız gruplar adlandırılmış grupların önündedir.
Yapıları gruplama genellikle yalnızca birden çok dil öğelerine nicel niceller uygulamak için kullanılır ve yakalanan alt dizeler ilginiz olmaz. Örneğin, aşağıdaki normal ifade:
\b\(?((\w+),?\s?)+[\.!?]\)?
yalnızca bir belgeden nokta, ünlem işareti veya soru işaretiyle sona eren cümleleri ayıklamak için tasarlanmıştır; yalnızca sonuçta elde edilen tümce (nesne tarafından Match temsil edilen) ilgiyi gösterir. Koleksiyonda tek tek sözcükler değildir.
Normal ifade altyapısının hem hem de koleksiyon nesnelerini doldurmak gerektirerek daha sonra kullanılmayan grupları yakalaması GroupCollection CaptureCollection pahalı olabilir. Alternatif olarak, yalnızca geçerli yakalamaların ad alt ifade yapısı tarafından belirlenen açıkça adlandırılmış veya numaralı gruplar olduğunu belirtmek için seçeneğini veya satır içi RegexOptions.ExplicitCapture n seçeneğini (?< > ) kullanabilirsiniz.
Aşağıdaki örnek, yöntemi seçeneğiyle ve seçeneği olmadan çağrıldıklarında normal ifade deseni tarafından \b\(?((\w+),?\s?)+[\.!?]\)? Match döndürülen eşleşmeler hakkında bilgi RegexOptions.ExplicitCapture görüntüler. İlk yöntem çağrısının çıkışında da olduğu gibi, normal ifade altyapısı ve koleksiyon nesnelerini yakalanan alt dizeler hakkında GroupCollection CaptureCollection bilgilerle tamamen doldurmakta. İkinci yöntem olarak ayarlanmış olarak options çağrıldı RegexOptions.ExplicitCapture olduğundan, gruplara ilişkin bilgileri yakalamaz.
using System;
using System.Text.RegularExpressions;
public class Example
{
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: {0}", match.Value);
int groupCtr = 0;
foreach (Group group in match.Groups)
{
Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value);
groupCtr++;
int captureCtr = 0;
foreach (Capture capture in group.Captures)
{
Console.WriteLine(" Capture {0}: {1}", 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: {0}", match.Value);
int groupCtr = 0;
foreach (Group group in match.Groups)
{
Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value);
groupCtr++;
int captureCtr = 0;
foreach (Capture capture in group.Captures)
{
Console.WriteLine(" Capture {0}: {1}", 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 Example
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 | Description |
|---|---|
\b |
Bir sözcük sınırından başlama. |
\(? |
Açma parantezlerinin ("(") sıfır veya bir oluşumunu eşler. |
(?>\w+),? |
Ardından sıfır veya bir virgül gelen bir veya daha fazla sözcük karakteriyle eşler. Sözcük karakterleri eşlerken geri izleme yapma. |
\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 ya da bir boşluk karakteri birleşimini bir veya daha fazla kez eşler. |
[\.!?]\)? |
Üç noktalama işareti sembollerinden herhangi birini, ardından sıfır veya bir kapatma parantezi (")) ile eşler. |
Otomatik yakalamaları bastırmak (?n) için satır içi öğesini de kullanabilirsiniz. Aşağıdaki örnek, seçeneği yerine satır içi öğeyi kullanmak için önceki (?n) normal ifade desenini RegexOptions.ExplicitCapture kullanır.
using System;
using System.Text.RegularExpressions;
public class Example
{
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: {0}", match.Value);
int groupCtr = 0;
foreach (Group group in match.Groups)
{
Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value);
groupCtr++;
int captureCtr = 0;
foreach (Capture capture in group.Captures)
{
Console.WriteLine(" Capture {0}: {1}", 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 Example
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, otomatik yakalamaları grup bazında göstermeden önce (?n:) satır içi grup öğesini kullanabilirsiniz. Aşağıdaki örnek, dış gruptaki adsız yakalamaları gizlemesi için önceki desenin değişikliklerini ((?>\w+),?\s?) sağlar. Bunun, iç gruptaki adsız yakalamaları da bastırmış olduğunu unutmayın.
using System;
using System.Text.RegularExpressions;
public class Example
{
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: {0}", match.Value);
int groupCtr = 0;
foreach (Group group in match.Groups)
{
Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value);
groupCtr++;
int captureCtr = 0;
foreach (Capture capture in group.Captures)
{
Console.WriteLine(" Capture {0}: {1}", 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 Example
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 İfadeler
Varsayılan olarak, .NET'te normal ifadeler yorumlanır. Bir nesne örneği çağrıldı mı veya statik yöntem çağrıldı mı, normal ifade deseni bir dizi özel opcodes olarak ayrıştırıldı ve yorumlayıcı normal ifadeyi çalıştırmak için bu Regex Regex opcode'ları kullanır. Bu bir takas içerir: Normal ifade altyapısını başlatma maliyeti, çalışma zamanı performansına göre en aza indirgenebilir.
seçeneğini kullanarak yorumlanır normal ifadeler yerine derlenmiş RegexOptions.Compiled kullanabilirsiniz. Bu durumda, bir desen normal ifade altyapısına geçirilmesinde, bir dizi opcodes olarak ayrıştırıldı ve ardından microsoft ara diline (MSIL) dönüştürüldü. Bu, doğrudan ortak dil çalışma zamanının kullanımına geçirilmenizi sağlar. Derlenmiş normal ifadeler başlatma süresine göre çalışma zamanı performansını en üst düzeye çıkartır.
Not
Normal bir ifade yalnızca bir sınıf oluşturucusuz veya statik desen eşleştirme yönteminin parametresine değer RegexOptions.Compiled options Regex belirterek derlenebilirsiniz. Satır içi seçenek olarak kullanılamaz.
Derlenmiş normal ifadeleri hem statik hem de örnek normal ifadelerine yapılan çağrılarda kullanabilirsiniz. Statik normal ifadelerde, RegexOptions.Compiled seçeneği normal ifade desen eşleştirme options yönteminin parametresine geçirildi. Örnek normal ifadelerde, sınıf oluşturucusuza options Regex parametresine geçir edilir. Her iki durumda da gelişmiş performansa neden olur.
Ancak, performansta bu geliştirme yalnızca aşağıdaki koşullarda gerçekleşir:
Belirli Regex 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.
RegexNesnenin kapsamın dışında kullanılmasına izin verilmez, bu nedenle yeniden kullanılabilir.
Statik bir 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ınarak performans geliştirmesi mümkündür.)
Not
seçeneği yöntemiyle ilgisizdir ve önceden tanımlanmış derlenmiş normal ifadeleri RegexOptions.Compiled içeren özel amaçlı bir derleme Regex.CompileToAssembly oluşturur.
Boşluğu Yoksay
Varsayılan olarak, normal ifade desenlerinde boşluk önemlidir; normal ifade altyapısını giriş dizesinde bir boşluk karakteriyle eşleşmeye iter. Bu nedenle, " " ve \b\w+\s " " normal ifadesi \b\w+ kabaca eşdeğer normal ifadelerdir. Ayrıca, sayı işareti (#) normal ifade desende karşılaşıldısa, eşleşmesi için değişmez karakter olarak yorumlanır.
seçeneği RegexOptions.IgnorePatternWhitespace veya satır içi x seçeneği, bu varsayılan davranışı aşağıdaki gibi değiştirir:
Normal ifade desende kaçışsız boşluk yoksayılır. Bir normal ifade deseninin parçası olmak için boşluk karakterlerinin (örneğin, veya
\s" ") kaç olması\gerekir.Sayı işareti (#), değişmez karakter yerine açıklamanın başlangıcı olarak yorumlanır. Normal ifade desendeki karakterden sonraki karaktere veya dizenin sonuna kadar olan tüm
#\nmetinler açıklama olarak yorumlanır.
Ancak, aşağıdaki durumlarda, seçeneğini kullansanız bile normal ifadedeki boşluk karakterleri RegexOptions.IgnorePatternWhitespace yoksayılır:
Bir karakter sınıfı içindeki boşluk her zaman tam anlamıyla yorumlanır. Örneğin, normal ifade deseni tek
[ .,;:]bir boşluk karakteri, nokta, virgül, noktalı virgül veya iki nokta üst üste ile eştir.n , n ve n m gibi köşeli ayraçlı miktar nicel
{}{içinde,}{boşluklara izin,verilmez.}Örneğin, normal ifade deseni boşluk karakteri içerdiğinden bir ile üç basamak arasında herhangi\d{1, 3}bir basamak dizisiyle eşleşmez.Bir dil öğesinin tanıt olduğu bir karakter dizisi içinde boşluklara izin verilmez. Örnek:
Dil öğesi
(?:alt ifadesi, kapsülleme olmayan bir grubu temsil eder ve öğenin bölümü)eklenmiş(?:boşluklara sahip değildir. Desen(? :alt ifadesi, normal ifade altyapısı deseni ayrıştıramaya ve desen alt ifadesi alt ifadeyle eşleşmey olduğundan çalışma zamanında)bir ArgumentException( ?:)oluşturur.Unicode kategorisini veya adlandırılmış bloğu temsil eden dil öğesi
\p{}adı, öğenin bölümüne katıştırılmış\p{boşluk ekemez. Bir boşluk dahil ediyorsanız, öğesi çalışma zamanında ArgumentException bir atar.
Bu seçeneğin etkinleştirilmesi, genellikle ayrıştırması ve anlaması zor olan normal ifadelerin basitleştirilmesine yardımcı olur. Okunabilirliği artırır ve normal bir ifadenin belgelenene kadar devamını sağlar.
Aşağıdaki örnek, aşağıdaki normal ifade desenini tanımlar:
\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.
Bu model, yalnızca açık yakalamalar bölümünde tanımlanan düzene benzer, ancak RegexOptions.IgnorePatternWhitespace model boşluk boşluğu yok sayma seçeneğini kullanır.
using System;
using System.Text.RegularExpressions;
public class Example
{
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 Example
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, (?x) kalıp boşluk alanını yoksaymak için satır içi seçeneğini kullanır.
using System;
using System.Text.RegularExpressions;
public class Example
{
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 Example
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 mod
Varsayılan olarak, normal ifade motoru soldan sağa doğru arar. Seçeneğini kullanarak arama yönünü ters çevirebilirsiniz RegexOptions.RightToLeft . Arama, dizenin son karakter konumunda otomatik olarak başlar. Bir başlangıç konumu parametresi içeren, örneğin Regex.Match(String, Int32) , başlangıç konumu, aramanın başlayacağı en sağdaki karakter konumunun dizinidir.
Not
Sağdan sola düzendeki desenler yalnızca RegexOptions.RightToLeft options bir Regex sınıf oluşturucusunun veya statik kalıp eşleştirme yönteminin parametresine değer sağlanarak kullanılabilir. Satır içi seçeneği olarak kullanılamaz.
RegexOptions.RightToLeftSeçeneği yalnızca arama yönünü değiştirir; normal ifade modelini sağdan sola yorumlamaz. Örneğin, normal ifade \bb\w+\s "b" harfiyle başlayan ve ardından bir boşluk karakteri gelen sözcüklerle eşleşir. Aşağıdaki örnekte, giriş dizesi bir veya daha fazla "b" karakteri içeren üç sözcükten oluşur. İlk sözcük "b" ile başlar, ikincisi "b" ile biter ve üçüncüsü sözcüğün ortasında iki "b" karakteri içerir. Örnekteki Çıktının gösterdiği gibi, yalnızca ilk sözcük normal ifade düzeniyle eşleşir.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\bb\w+\s";
string input = "builder rob rabble";
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.RightToLeft))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
}
}
// The example displays the following output:
// 'builder ' found at position 0.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\bb\w+\s"
Dim input As String = "builder rob rabble"
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:
' 'builder ' found at position 0.
Ayrıca, ileriye doğru onaylama (alt (?= ifade ) dili öğesi) ve geriye doğru onaylama onay (alt (?<= ifade ) dili öğesi) yönünün değişmediğini unutmayın. İleri yönlü onaylar doğru görünür; geriye doğru arama onayları sola bakar. Örneğin, normal ifade, (?<=\d{1,2}\s)\w+,?\s\d{4} bir ay adından önce gelen bir tarihi sınamak için geriye yönelik onaylama onayını kullanır. Normal ifade daha sonra month ve Year ile eşleşir. İleri ve geriye yönelik onaylar hakkında daha fazla bilgi için bkz. gruplandırma yapıları.
using System;
using System.Text.RegularExpressions;
public class Example
{
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 {0}.", match.Value);
else
Console.WriteLine("{0} does not match.", input);
}
}
}
// The example displays the following output:
// The date occurs in May 1917.
// June 16, 2003 does not match.
Imports System.Text.RegularExpressions
Module Example
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 deseninin, aşağıdaki tabloda gösterildiği gibi tanımlanmıştır.
| Desen | Description |
|---|---|
(?<=\d{1,2}\s) |
Eşleşmenin başlangıcında bir veya iki ondalık basamak gelmeli ve ardından bir boşluk gelmelidir. |
\w+ |
Bir veya daha fazla sözcük karakteri eşleştir. |
,? |
Sıfır veya 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ı bir normal ifade örüntüsünün giriş metnine eşleştirilirken kurallı davranışı kullanır. Ancak, normal ifade altyapısından, seçeneğini belirterek ECMAScript eşleştirme davranışı kullanmasını söyleyebilirsiniz RegexOptions.ECMAScript .
Not
ECMAScript uyumlu davranış yalnızca RegexOptions.ECMAScript options bir Regex sınıf oluşturucusunun veya statik kalıp eşleştirme yönteminin parametresine değeri sağlanarak kullanılabilir. Satır içi seçeneği olarak kullanılamaz.
RegexOptions.ECMAScriptSeçeneği yalnızca RegexOptions.IgnoreCase ve RegexOptions.Multiline seçenekleriyle birleştirilebilir. Normal ifadede herhangi bir diğer seçeneğin kullanılması bir ile sonuçlanır ArgumentOutOfRangeException .
ECMAScript ve kurallı normal ifadelerin davranışı üç alanda farklılık gösterir: karakter sınıfı sözdizimi, kendine başvuran yakalama grupları ve sekizlik ve geri başvuru yorumu.
Karakter sınıfı sözdizimi. Geleneksel normal ifadeler Unicode desteklediği için ECMAScript, ECMAScript 'teki karakter sınıfları daha sınırlı sözdizimine sahiptir ve bazı karakter sınıfı dil öğeleri farklı anlamdadır. Örneğin, ECMAScript, Unicode kategorisi veya blok öğeleri ve gibi dil öğelerini desteklemez
\p\P. Benzer şekilde,\wbir sözcük karakteriyle eşleşen öğe,[a-zA-Z_0-9]ECMAScript kullanılırken ve kurallı davranış kullanılırken karakter sınıfına eşdeğerdir[\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}]. Daha fazla bilgi için bkz. karakter sınıfları.Aşağıdaki örnek kurallı ve ECMAScript desenli eşleştirme arasındaki farkı gösterir. Bir normal ifade tanımlar, ve
\b(\w+\s*)+ardından boşluk karakterleri gelen kelimelerle eşleşir. Giriş, biri Latin karakter kümesini ve diğeri ise Kiril karakter kümesini kullanan iki dizeden oluşur. Çıktıda gösterildiği gibi, Regex.IsMatch(String, String, RegexOptions) ECMAScript eşleştirmeyi kullanan yönteme yapılan çağrı, Kiril kelimeleri ile eşleşemez, ancak 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 Example { 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("'{0}' matches the pattern.", value); else Console.WriteLine("{0} does not match the pattern.", value); Console.Write("ECMAScript matching: "); if (Regex.IsMatch(value, pattern, RegexOptions.ECMAScript)) Console.WriteLine("'{0}' matches the pattern.", value); else Console.WriteLine("{0} does not match the pattern.", value); 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 Example 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) 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) 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.Kendine başvuran yakalama grupları. Kendisi için geri başvuru içeren bir normal ifade yakalama sınıfı, her yakalama yinelemesi ile güncelleştirilmeleri gerekir. Aşağıdaki örnekte gösterildiği gibi, bu özellik, normal ifadenin
((a+)(\1) ?)+ECMAScript kullanılırken "aa aaaa aaaaaa" giriş dizesiyle eşleşmesini sağlar, ancak kurallı eşleştirme kullanılırken değildir.using System; using System.Text.RegularExpressions; public class Example { 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("'{0}' matches {1} at position {2}.", pattern, m.Value, m.Index); int grpCtr = 0; foreach (Group grp in m.Groups) { Console.WriteLine(" {0}: '{1}'", grpCtr, grp.Value); grpCtr++; int capCtr = 0; foreach (Capture cap in grp.Captures) { Console.WriteLine(" {0}: '{1}'", 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 Example 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 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ımlanmıştır.
Desen Description (+) "A" harfini bir veya daha fazla kez eşleştirin. Bu ikinci yakalama grubudur. (\ 1) İlk yakalama grubu tarafından yakalanan alt dizeyle eşleştirin. Bu, üçüncü yakalama grubudur. ? Sıfır veya bir boşluk karakterini eşleştirin. ((a +) (\ 1)?) + Bir veya daha fazla "a" karakterinin örüntüsünün ardından ilk yakalama grubuyla eşleşen bir dize ve ardından sıfır veya bir boşluk karakteri bir veya daha fazla kez olacak şekilde eşleşen bir karakter. Bu ilk yakalama grubudur. Sekizlik kaçış ve geri başvurular arasında belirsizlikleri çözümlemesi. Aşağıdaki tabloda, kurallı ve ECMAScript normal ifadelerine karşılık gelen sekizlik ve geribaşvuru yorumlamasının farkları özetlenmektedir.
Normal ifade Kurallı davranış ECMAScript davranışı \0ardından 0 ile 2 sekizlik basamakSekizlik olarak yorumlayın. Örneğin, \044her zaman sekizlik bir değer olarak yorumlanır ve "$" anlamına gelir.Aynı davranış. \ardından 1 ile 9 arasında bir basamak, ardından ek ondalık basamak yok,Bir geri başvuru olarak yorumlayın. Örneğin, \9bir dokuzuncu yakalama grubu mevcut olmasa bile her zaman geri başvuru 9 anlamına gelir. Yakalama grubu yoksa, normal ifade ayrıştırıcısı bir oluşturur ArgumentException .Tek bir ondalık basamak yakalama grubu varsa, bu basamağa geri başvuru. Aksi takdirde, değeri değişmez değer olarak yorumlayın. \ardından, 1 ile 9 arasında bir rakam ve ardından ek ondalık basamaklarBasamakları ondalık değer olarak yorumlayın. Bu yakalama grubu varsa, ifadeyi bir geri başvuru olarak yorumlayın.
Aksi takdirde, önde gelen sekizlik basamakları sekizlik 377 ' e kadar yorumlayın; diğer bir deyişle, yalnızca değerin düşük 8 bitini göz önünde bulundurun. Kalan basamakları değişmez değer olarak yorumlayın. Örneğin ifadesinde,\3000grup 300 yakalama varsa, geri başvuru 300 olarak yorumlayın; grup 300 yakalama yoksa, sekizlik 300 olarak, ardından 0 olarak yorumlayın.Bir yakalamaya başvurabilen ondalık bir değere mümkün olduğunca çok basamak dönüştürerek bir geri başvuru olarak yorumlayın. Herhangi bir basamak dönüştürülemiyorsa, sekizlik basamağı 377 ' e kadar olan önde gelen sekizlik basamakları kullanarak sekizlik olarak yorumlayın; kalan basamakları değişmez değer olarak yorumlayın.
Sabit kültür kullanılarak 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 harfli karakterleri anlamak için geçerli kültürün büyük/küçük harf kurallarını kullanır.
Ancak, özellikle Kullanıcı girişini parolalar, dosyalar veya URL 'Ler gibi sistem kaynaklarının adlarıyla karşılaştırırken, bu davranış bazı karşılaştırmalar türleri için istenmeyen bir durum değildir. Aşağıdaki örnek senaryo gibi gösterilmektedir. Kod, URL 'SI FILE:// ile kullanıma hazır olan herhangi bir kaynağa erişimi engellemeye yöneliktir. Normal ifade, normal ifade kullanarak dizeyle büyük/küçük harfe duyarsız bir eşleştirme girişiminde bulunur $FILE:// . Ancak, geçerli sistem kültürü tr-TR (Türkçe-Türkiye) olduğunda "I", "i" öğesinin büyük harfli eşdeğeri değildir. Sonuç olarak, yöntemine yapılan çağrı Regex.IsMatch döner false 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 ({0} culture)...",
Thread.CurrentThread.CurrentCulture.Name);
if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("URLs that access files are not allowed.");
else
Console.WriteLine("Access to {0} is allowed.", input);
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ı ve sabit kültür kullanan dize karşılaştırmaları hakkında daha fazla bilgi için bkz. dizeleri kullanmak Için En Iyi uygulamalar.
Geçerli kültürün büyük/küçük harf duyarsız karşılaştırmalarını kullanmak yerine, RegexOptions.CultureInvariant dildeki kültürel farklılıklarını yok sayma ve sabit kültürün kurallarını kullanma seçeneğini belirtebilirsiniz.
Not
Sabit kültür kullanılarak karşılaştırma yalnızca RegexOptions.CultureInvariant options bir Regex sınıf oluşturucusunun veya statik kalıp eşleştirme yönteminin parametresine değeri sağlanarak kullanılabilir. Satır içi seçeneği olarak kullanılamaz.
Aşağıdaki örnek, bir önceki örnekle aynıdır, ancak statik Regex.IsMatch(String, String, RegexOptions) Yöntem dahil olan seçeneklerle çağırılır RegexOptions.CultureInvariant . Geçerli kültür Türkçe (Türkiye) olarak ayarlandığında bile, normal ifade altyapısı "dosya" ve "dosya" ile başarılı bir şekilde eşleştirebilir ve 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 {0} is allowed.", input);
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.