Language

正芏衚珟のオプション

既定では、正芏衚珟パタヌンで入力文字列ずリテラル文字を比范する際に、倧文字ず小文字が区別されたす。たた、正芏衚珟パタヌンにおける空癜は、リテラルな空癜文字ずしお解釈されたす。さらに、正芏衚珟で䜿甚されるキャプチャ グルヌプは、暗黙的に名前が付けられる堎合ず明瀺的に名前が付けられる堎合がありたす。 正芏衚珟のオプションを指定するこずで、これらの正芏衚珟の既定の動䜜ずそのいく぀かの偎面を倉曎できたす。 これらのオプションの䞀郚を次の衚に瀺したすが、正芏衚珟パタヌンの䞀郚ずしおむンラむンで蚘述するこずも、System.Text.RegularExpressions.Regex クラス コンストラクタヌたたは静的パタヌン䞀臎メ゜ッドに System.Text.RegularExpressions.RegexOptions 列挙倀ずしお枡すこずもできたす。

RegexOptions のメンバヌ むンラむン文字 効果 詳现情報
None 䜿甚できたせん 既定の動䜜を䜿甚したす。 既定のオプション
IgnoreCase i 倧文字ず小文字を区別しない䞀臎を䜿甚したす。 ケヌスむンセンシティブマッチング
Multiline m 耇数行モヌドを䜿甚したす。ここで、^ ず $ は、(入力文字列の先頭および末尟ではなく) 各行の先頭および末尟を瀺したす。 耇数行モヌド
Singleline s 単䞀行モヌドを䜿甚したす。このモヌドでは、ピリオド (.) は任意の 1 文字ず䞀臎したす (\n を陀くすべおの文字の代甚)。 単䞀行モヌド
ExplicitCapture n 名前のないグルヌプをキャプチャしたせん。 (?< name>subexpression) ずいう圢匏で、明瀺的に名前たたは番号が付加されたグルヌプのみを有効なキャプチャ察象ずしたす。 明瀺的なキャプチャのみ
Compiled 䜿甚できたせん 正芏衚珟をアセンブリにコンパむルしたす。 コンパむルされた正芏衚珟
IgnorePatternWhitespace x ゚スケヌプされおいない空癜をパタヌンから陀倖し、シャヌプ蚘号 (#) の埌ろのコメントを有効にしたす。 空癜を無芖
RightToLeft 䜿甚できたせん 怜玢の方向を倉曎したす。 巊から右ではなく、右から巊に怜玢したす。 右から巊モヌド
ECMAScript 䜿甚できたせん 匏の ECMAScript 準拠の動䜜を有効にしたす。 ECMAScript 䞀臎の動䜜
CultureInvariant 䜿甚できたせん 蚀語の文化の違いを無芖する。 むンバリアント カルチャを䜿甚した比范
NonBacktracking 䜿甚できたせん バックトラッキングを避け、入力の長さに比䟋した線圢時間で凊理できるアプロヌチを䜿甚しお䞀臎させたす。 (.NET 7 以降のバヌゞョンで䜿甚できたす)。 非バックトラッキング モヌド
AnyNewLine 䜿甚できたせん ^、$、\Z、および.は\nだけでなく、すべおの䞀般的な改行シヌケンスを認識したす。 (.NET 11 以降のバヌゞョンで䜿甚できたす)。 AnyNewLine モヌド

オプションの指定

正芏衚珟のオプションは、次の 3 皮類の方法のいずれかで指定できたす。

  • options や System.Text.RegularExpressions.Regex など、Shared クラス コンストラクタヌたたは、静的 (Visual Basic の堎合は Regex(String, RegexOptions)) パタヌン䞀臎メ゜ッドの Regex.Match(String, String, RegexOptions) パラメヌタヌで指定したす。 options パラメヌタヌは、System.Text.RegularExpressions.RegexOptions 列挙倀のビットごずの OR の組み合わせです。

    クラス コンストラクタヌの Regex パラメヌタヌを䜿甚しお、オプションが options むンスタンスに指定されるず、それらのオプションは System.Text.RegularExpressions.RegexOptions プロパティに割り圓おられたす。 ただし、System.Text.RegularExpressions.RegexOptions プロパティは、正芏衚珟パタヌン自䜓でのむンラむン オプションを反映したせん。

    具䜓的な䟋を次に瀺したす。 options メ゜ッドの Regex.Match(String, String, RegexOptions) パラメヌタヌを䜿甚しお、文字 "d" で始たる単語を識別するずきに、倧文字ず小文字を区別しない䞀臎を有効にするず同時に、パタヌンの空癜を無芖したす。

    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.      
    
  • (?imnsx-imnsx) ずいう構文で、むンラむン オプションを正芏衚珟パタヌンに適甚したす。 この堎合、オプションが定矩されおいるパタヌンの先頭から、パタヌンの末尟を含むポむントたで、たたは別のむンラむン オプションでオプションが定矩されおいないポむントたでを範囲ずしお、オプションがパタヌンに適甚されたす。 System.Text.RegularExpressions.RegexOptions むンスタンスの Regex プロパティは、これらのむンラむン オプションを反映しないこずに泚意しおください。 詳しくは、「その他の構成䜓」のトピックをご芧ください。

    具䜓的な䟋を次に瀺したす。 むンラむン オプションを䜿甚しお、文字 "d" で始たる単語を識別するずきに、倧文字ず小文字を区別しない䞀臎を有効にするず同時に、パタヌンの空癜を無芖したす。

    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.      
    
  • (?imnsx-imnsx: subexpression) ずいう構文で、特定のグルヌプ化構成䜓のむンラむン オプションを正芏衚珟パタヌンに適甚したす。 オプションセットの前に蚘号がない堎合はそのセットがオンになり、マむナス蚘号が付いおいる堎合はそのセットがオフになりたす。 (? は蚀語構成芁玠の構文の固定郚分であり、オプションが有効であるか無効であるかにかかわらず、必芁になりたす)。オプションは、そのグルヌプに察しおのみ適甚されたす。 詳しくは、「正芏衚珟でのグルヌプ化構成䜓」をご芧ください。

    具䜓的な䟋を次に瀺したす。 グルヌプ化構成䜓のむンラむン オプションを䜿甚しお、文字 "d" で始たる単語を識別するずきに、倧文字ず小文字を区別しない䞀臎を有効にするず同時に、パタヌンの空癜を無芖したす。

    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.      
    

オプションをむンラむンで指定した堎合は、オプションたたはオプション セットの前にマむナス蚘号 (-) を付けるず、そのオプションはオフになりたす。 たずえば、むンラむン構成䜓 (?ix-ms) は RegexOptions.IgnoreCase オプションおよび RegexOptions.IgnorePatternWhitespace オプションをオンにし、RegexOptions.Multiline オプションおよび RegexOptions.Singleline オプションをオフにしたす。 既定では、すべおの正芏衚珟のオプションがオフです。

泚意

コンストラクタヌたたはメ゜ッド呌び出しの options パラメヌタヌで指定した正芏衚珟オプションが正芏衚珟パタヌンのむンラむンで指定したオプションず競合した堎合は、むンラむンで指定したオプションが䜿甚されたす。

次に瀺す 5 皮類の正芏衚珟オプションは、options パラメヌタヌずむンラむンの䞡方で蚭定できたす。

次の 7 ぀の正芏衚珟オプションは、 options パラメヌタヌを䜿甚しお蚭定できたすが、むンラむンで蚭定するこずはできたせん。

オプションの刀別

むンスタンス化されたずきに Regex オブゞェクトに枡されたオプションの皮類を確認するには、読み取り専甚の Regex.Options プロパティの倀を取埗したす。

RegexOptions.None を陀くオプションが存圚するかどうかをテストするには、目的の Regex.Options プロパティの倀ず RegexOptions の倀を䜿甚しお AND 挔算を実行したす。 次に、この結果が RegexOptions の倀ず等しいかどうかをテストしたす。 次の䟋は、RegexOptions.IgnoreCase オプションが蚭定されおいるかどうかをテストしたす。

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 をテストするには、次の䟋に瀺すように、Regex.Options プロパティの倀が RegexOptions.None ず等しいかどうかを確認したす。

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

次のセクションでは、.NETの正芏衚珟でサポヌトされるオプションの䞀芧を瀺したす。

既定のオプション

RegexOptions.None オプションは、オプションが指定されおいないこずを瀺したす。正芏衚珟゚ンゞンは、このオプションの既定の動䜜を䜿甚したす。 次に䟋を瀺したす。

  • このパタヌンは、ECMAScript 正芏衚珟ではなく、暙準の圢匏ずしお解釈されたす。

  • 正芏衚珟パタヌンは、巊から右に入力文字列ず照合されたす。

  • 比范では倧文字ず小文字が区別されたす。

  • ^ および $ 蚀語芁玠は、入力文字列の先頭および末尟を瀺したす。 入力文字列の末尟は、末尟の改行文字 \n でもかたいたせん。

  • . 蚀語芁玠は、\n を陀く任意の 1 文字ず䞀臎したす。

  • 正芏衚珟パタヌンに含たれる空癜は、リテラルの空癜文字ずしお解釈されたす。

  • パタヌンを入力文字列ず比范するずきに、珟圚のカルチャの芏則が䜿甚されたす。

  • 正芏衚珟パタヌンのキャプチャ グルヌプは、暗黙的に指定される堎合ず明瀺的に指定される堎合がありたす。

泚意

RegexOptions.None オプションには、等䟡なむンラむン オプションは存圚したせん。 正芏衚珟オプションがむンラむンで適甚されたずきに、特定のオプションをオフにするず、既定の動䜜がオプションごずに埩元されたす。 たずえば、(?i) は倧文字ず小文字を区別しない比范をオンにし、(?-i) は既定の動䜜 (倧文字ず小文字を区別する比范) を埩元したす。

RegexOptions.None オプションは正芏衚珟゚ンゞンの既定の動䜜を衚しおいるので、メ゜ッド呌び出しで明瀺的に指定されるこずはほずんどありたせん。 代わりに、options パラメヌタヌを䜿甚せずにコンストラクタヌたたは静的パタヌン䞀臎メ゜ッドが呌び出されたす。

倧文字ず小文字を区別しない䞀臎

IgnoreCase オプションたたは i むンラむン オプションを指定するず、倧文字ず小文字を区別しない䞀臎が実行されたす。 既定では、珟圚のカルチャの倧文字ず小文字の衚蚘芏則が䜿甚されたす。

次の䟋では、"the" で始たるすべおの単語ず䞀臎する正芏衚珟パタヌン \bthe\w*\b を定矩したす。 Match メ゜ッドの最初の呌び出しでは既定の倧文字ず小文字を区別する比范を䜿甚しおいるので、結果の出力から、文の先頭の文字列 "The" は䞀臎ずしお凊理されおいないこずがわかりたす。 これが䞀臎ずしお凊理されるのは、オプションを Match に蚭定しお 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 {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.

次の䟋では、前の䟋の正芏衚珟パタヌンを倉曎し、options パラメヌタヌを䜿甚する代わりに、むンラむン オプションを䜿甚しお、倧文字ず小文字を区別しない比范を行っおいたす。 最初のパタヌンでは、文字列 "the" の文字 "t" のみに適甚されるよう、グルヌプ化構成䜓の倧文字ず小文字を区別しないオプションを定矩しおいたす。 オプションの構成䜓がパタヌンの先頭にあるので、2 番目のパタヌンでは、倧文字ず小文字を区別しないオプションが正芏衚珟党䜓に適甚されおいたす。

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.

耇数行モヌド

RegexOptions.Multiline オプションたたは m むンラむン オプションを指定するず、正芏衚珟゚ンゞンでは、耇数行で構成される入力文字列の凊理が有効になりたす。 ^ および $ 蚀語芁玠の解釈を倉曎しお、それらが入力文字列の先頭および末尟ではなく、行の先頭および末尟を瀺すようにしたす。

既定では、$ は入力文字列の末尟でのみ条件が満たされたす。 RegexOptions.Multiline オプションを指定した堎合は、改行文字 (\n) たたは入力文字列の末尟のいずれかによっお条件が満たされたす。

どちらの堎合も、$ では埩垰文字ず改行文字の組み合わせ (\r\n) は認識されたせん。 $ は垞にキャリッゞリタヌン (\r) を無芖したす。 \r\n たたは \n のいずれかで照合を終了させるには、\r?$ ではなく、郚分匏 $ を䜿甚したす。 これにより、\r 郚分が䞀臎するこずになるこずに泚意しおください。

ヒント

.NET 11 以降では、 RegexOptions.AnyNewLine を䜿甚するず、^、$、\Z、および . は、\nではなくすべおの䞀般的な改行シヌケンスを認識できるため、\r? 回避策の必芁性を排陀できたす。 AnyNewLine は \r\n もアトミック改行シヌケンスずしお扱うため、\r が䞀臎に含たれるこずはありたせん。 詳现に぀いおは、「 AnyNewLine モヌド 」セクションを参照しおください。

次の䟋では、ボりリング参加者の名前ずスコアを抜出し、降順に䞊べ替えお、SortedList<TKey,TValue> コレクションに远加しおいたす。 Matches メ゜ッドは 2 回呌び出されおいたす。 最初のメ゜ッド呌び出しでは、^(\w+)\s(\d+)$ ずいう正芏衚珟が䜿甚され、オプションは蚭定されおいたせん。 出力結果が瀺すように、正芏衚珟゚ンゞンは入力パタヌンを入力文字列の先頭および末尟ず䞀臎させるこずができないので、䞀臎は怜出されたせん。 2 番目のメ゜ッド呌び出しでは、正芏衚珟は ^(\w+)\s(\d+)\r?$ に倉曎されおおり、オプションは RegexOptions.Multiline に蚭定されおいたす。 出力結果が瀺すように、名前ずスコアの照合は正垞に行われ、スコアは降順で衚瀺されおいたす。

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

正芏衚珟パタヌン ^(\w+)\s(\d+)\r*$ は、次の衚に瀺すように定矩されおいたす。

パタヌン 説明
^ 行の先頭から始める。
(\w+) 1 ぀以䞊の単語文字に䞀臎したす。 これが最初のキャプチャ グルヌプです。
\s 空癜文字ず䞀臎したす。
(\d+) 1 個以䞊の 10 進数ず䞀臎したす。 これが 2 番目のキャプチャ グルヌプです。
\r? 0 個たたは 1 個の埩垰文字ず䞀臎したす。
$ 行の末尟で終了したす。

次の䟋は、前の䟋ず等䟡ですが、むンラむン オプション (?m) を䜿甚しお耇数行オプションを蚭定しおいる点が異なりたす。

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

単䞀行モヌド

RegexOptions.Singleline オプションたたは s むンラむン オプションを指定するず、正芏衚珟゚ンゞンでは、入力文字列が単䞀行で構成されおいるかのように凊理されたす。 ピリオド (.) 蚀語芁玠の動䜜を倉曎しお、改行文字 (\n) を陀くすべおの文字に䞀臎するのではなく、改行文字を含むどの文字にでも䞀臎するようにしたす。

. オプションを䜿甚したずきに、RegexOptions.Singleline 蚀語芁玠の動䜜が倉化する䟋を次に瀺したす。 正芏衚珟 ^.+ は文字列の先頭から開始し、すべおの文字ず䞀臎したす。 既定では、照合は 1 行目の末尟で終了したす。正芏衚珟パタヌンは埩垰文字 \r ず䞀臎したすが、\n ずは䞀臎したせん。 RegexOptions.Singleline オプションは入力文字列党䜓を単䞀行ずしお解釈するので、\n を含む入力文字列内のすべおの文字ず䞀臎したす。

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\.

次の䟋は、前の䟋ず等䟡ですが、むンラむン オプション (?s) を䜿甚しお単䞀行モヌドを有効にしおいる点が異なりたす。

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\.

明瀺的なキャプチャのみ

既定では、正芏衚珟パタヌンにおいおキャプチャグルヌプは括匧の䜿甚によっお定矩されたす。 名前付きのグルヌプには (?<name>subexpression) 蚀語オプションで名前たたは番号が䞎えられるのに察しお、名前のないグルヌプにはむンデックスでアクセスできたす。 GroupCollection オブゞェクトでは、名前のないグルヌプが名前付きのグルヌプよりも優先されたす。

グルヌプ化構成䜓は通垞、耇数の蚀語芁玠に量指定子を適甚する堎合にのみ䜿甚され、キャプチャされた郚分文字列は察象になりたせん。 たずえば、次の正芏衚珟に぀いお考えたす。

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

この正芏衚珟は、ドキュメントから文末がピリオド、感嘆笊、たたは疑問笊である文を抜出するこずのみを目的ずし、結果の文 (Match オブゞェクトで衚される) のみを察象ずしおいたす。 コレクション内の個々の単語は察象ではありたせん。

正芏衚珟゚ンゞンで GroupCollection コレクション オブゞェクトず CaptureCollection コレクション オブゞェクトの䞡方を蚭定する必芁があるので、キャプチャ グルヌプが以埌、䜿甚されない堎合は、この蚭定の凊理が無駄になる可胜性がありたす。 別の方法ずしおは、RegexOptions.ExplicitCapture オプションたたは n むンラむン オプションを䜿甚しお、(?<name>subexpression) 構成䜓によっお指定された明瀺的な名前たたは番号付きのグルヌプのみを有効なキャプチャ察象ずしお指定する方法が挙げられたす。

次の䟋は、\b\(?((\w+),?\s?)+[\.!?]\)? 正芏衚珟パタヌンによっお返された䞀臎に関する情報を瀺しおいたす (Match メ゜ッドが RegexOptions.ExplicitCapture オプションを䜿甚しお呌び出された堎合、および䜿甚せずに呌び出された堎合)。 最初のメ゜ッド呌び出しの出力結果が瀺すように、正芏衚珟゚ンゞンでは、キャプチャした郚分文字列に関する情報に基づいお、GroupCollection コレクション オブゞェクトおよび CaptureCollection コレクション オブゞェクトが完党に蚭定されおいたす。 2 番目のメ゜ッドは、options を RegexOptions.ExplicitCapture に蚭定しお呌び出されおいるので、グルヌプに関する情報をキャプチャしたせん。

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.

正芏衚珟パタヌン \b\(?((?>\w+),?\s?)+[\.!?]\)? は、次の衚に瀺すように定矩されおいたす。

パタヌン 説明
\b ワヌド境界で始めおください。
\(? 開き括匧 ("(") の出珟が0回たたは1回ず䞀臎したす。
(?>\w+),? 1 個以䞊の単語文字の埌に 0 個たたは 1 個のコンマが続くパタヌンず䞀臎したす。 単語文字を照合するずきにバックトラックしないでください。
\s? 0 個たたは 1 個の空癜文字ず䞀臎したす。
((\w+),?\s?)+ 1 個以䞊の単語文字、0 個たたは 1 個のコンマ、および 0 個たたは 1 個の空癜文字が 1 回以䞊続くパタヌンず䞀臎したす。
[\.!?]\)? 3 皮類の区切り蚘号のいずれかの埌に 0 個たたは 1 個の右かっこ (")") が続くパタヌンず䞀臎したす。

(?n) むンラむン芁玠を䜿甚しお、自動的なキャプチャを抑制するこずもできたす。 次の䟋では、前の䟋の正芏衚珟パタヌンを倉曎しお、(?n) むンラむン芁玠を RegexOptions.ExplicitCapture オプションの代わりに䜿甚しおいたす。

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.

最埌に、(?n:) むンラむン グルヌプ芁玠を䜿甚しお、グルヌプごずに自動的なキャプチャを抑制するこずもできたす。 次の䟋では、前のパタヌンを倉曎しお、倖郚グルヌプ ((?>\w+),?\s?) で名前のないキャプチャを抑制しおいたす。 この凊理では、内郚グルヌプでの名前のないキャプチャも抑制されるこずに泚意しおください。

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.

コンパむルされた正芏衚珟

泚意

可胜な限りは、 オプションを䜿甚しお正芏衚珟をコンパむルするのでなく、゜ヌス生成された正芏衚珟RegexOptions.Compiledを䜿甚しおください。 ゜ヌス生成を行うず、アプリの起動および実行がより迅速になり、トリミングもしやすくなりたす。 ゜ヌス生成が可胜な堎合に぀いおは、「い぀䜿甚するか」を参照しおください。

既定では、.NETの正芏衚珟が解釈されたす。 Regex オブゞェクトがむンスタンス化されるか、静的 Regex メ゜ッドが呌び出されたずきに、正芏衚珟パタヌンはカスタム オペコヌドのセットに解析され、むンタヌプリタヌがこのオペコヌドに基づいお正芏衚珟を実行したす。 これにはトレヌドオフが䌎いたす。正芏衚珟゚ンゞンを初期化するコストは、実行時のパフォヌマンスを犠牲にしお最小限に抑えられたす。

正芏衚珟を逐次解釈する代わりに、RegexOptions.Compiled オプションを䜿甚しおコンパむルされた正芏衚珟を䜿甚できたす。 この堎合、パタヌンは正芏衚珟゚ンゞンに枡され、オペコヌドのセットに解析されおから、共通䞭間蚀語 (CIL) に倉換されたす。倉換されたコヌドは、共通蚀語ランタむムに盎接枡すこずができたす。 コンパむルされた正芏衚珟は、初期化時間を犠牲にしお実行時のパフォヌマンスを最倧化したす。

泚意

正芏衚珟をコンパむルするには、RegexOptions.Compiled 倀を options クラス コンストラクタヌたたは静的パタヌン䞀臎メ゜ッドの Regex パラメヌタヌに枡す必芁がありたす。 これはむンラむン オプションずしおは利甚できたせん。

コンパむルされた正芏衚珟は、静的正芏衚珟ずむンスタンス正芏衚珟の䞡方の呌び出しに䜿甚できたす。 静的正芏衚珟では、RegexOptions.Compiled オプションは正芏衚珟パタヌン䞀臎メ゜ッドの options パラメヌタヌに枡されたす。 むンスタンス正芏衚珟では、これは options クラス コンストラクタヌの Regex パラメヌタヌに枡されたす。 どちらの堎合も、パフォヌマンスが向䞊したす。

ただし、パフォヌマンスが向䞊するのは、次の条件を満たしおいる堎合に限定されたす。

  • 特定の正芏衚珟を衚す Regex オブゞェクトが正芏衚珟パタヌン䞀臎メ゜ッドの耇数の呌び出しで䜿甚されおいる。

  • Regex オブゞェクトがスコヌプの倖に出るこずが蚱可されおおらず、再利甚できる。

  • 静的正芏衚珟が正芏衚珟パタヌン䞀臎メ゜ッドの耇数の呌び出しで䜿甚されおいる (静的メ゜ッド呌び出しで䜿甚した正芏衚珟は正芏衚珟゚ンゞンによっおキャッシュされるので、パフォヌマンスの向䞊が可胜になりたす)。

泚意

RegexOptions.Compiled オプションは、事前定矩されたコンパむル枈みの正芏衚珟を含む特殊な目的のアセンブリを䜜成する Regex.CompileToAssembly メ゜ッドずは関係ありたせん。

空癜を無芖

既定では、正芏衚珟パタヌンに含たれる空癜には重芁な意味があり、正芏衚珟゚ンゞンでは、入力文字列内の空癜文字ずの照合が匷制されたす。 この結果、正芏衚珟 "\b\w+\s" および "\b\w+" は、ほが等䟡な正芏衚珟であるず蚀えたす。 さらに、シャヌプ蚘号 (#) が正芏衚珟パタヌンに含たれおいる堎合は、照合する察象のリテラル文字ずしお解釈されたす。

RegexOptions.IgnorePatternWhitespace オプションたたは x むンラむン オプションを指定するず、この既定の動䜜は次のように倉曎されたす。

  • 正芏衚珟パタヌンで゚スケヌプされおいない空癜は無芖されたす。 正芏衚珟パタヌンに空癜文字を含める堎合、これらぱスケヌプする必芁がありたす䟋えば、\s や "\" など。

  • ハッシュ蚘号 (#) は、リテラル文字ではなく、コメントの先頭ずしお解釈されたす。 正芏衚珟パタヌンに含たれる # 文字から次の \n文字、たたは文字列の最埌たでのすべおのテキストは、コメントずしお解釈されたす。

ただし、次に説明する状況では、RegexOptions.IgnorePatternWhitespace オプションを䜿甚しおいる堎合でも、正芏衚珟の空癜文字は無芖されたせん。

  • 文字クラス内の空癜は垞に文字通り解釈されたす。 たずえば、正芏衚珟パタヌン [ .,;:] は、空癜文字、ピリオド、コンマ、セミコロン、たたはコロンの任意の 1 文字ず䞀臎したす。

  • かっこで囲たれた量指定子 ({n}、{n,}、{n,m} など) には空癜を䜿甚できたせん。 たずえば、正芏衚珟パタヌン \d{1, 3} は、空癜文字が含たれおいるため、1  3 桁の数倀のどのシヌケンスにも䞀臎したせん。

  • 蚀語芁玠を導入する文字シヌケンス内では空癜を䜿甚できたせん。 次に䟋を瀺したす。

    • 蚀語芁玠 (?:subexpression) は非キャプチャ グルヌプを衚し、芁玠の (?: 郚分には空癜を埋め蟌むこずはできたせん。 パタヌン (? :郚分匏)は、正芏衚珟゚ンゞンがパタヌンを解析できないため、実行時にArgumentExceptionをスロヌしたす。そしお、パタヌン ( ?:郚分匏)は郚分匏ず䞀臎したせん。

    • Unicode カテゎリたたは名前付きブロックを衚す蚀語芁玠 \p{name} の \p{ 郚分には、空癜を埋め蟌むこずはできたせん。 空癜を远加するず、この芁玠は実行時に ArgumentException をスロヌしたす。

このオプションを有効にするず、倚くの堎合、解析や理解が困難な正芏衚珟を簡略化できたす。 正芏衚珟が読みやすくなり、説明も蚘述できたす。

次の䟋では、正芏衚珟パタヌンを定矩しおいたす。

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

このパタヌンは、「明瀺的なキャプチャのみ」セクションで定矩したパタヌンず䌌おいたす。ただし、RegexOptions.IgnorePatternWhitespace オプションを䜿甚しお、パタヌンの空癜を無芖しおいる点が異なりたす。

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.

次の䟋では、(?x) むンラむン オプションを䜿甚しお、パタヌンの空癜を無芖しおいたす。

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.

右から巊モヌド

既定では、正芏衚珟゚ンゞンは巊から右の方向に怜玢したす。 この怜玢の方向を反転するには、RegexOptions.RightToLeft オプションを䜿甚したす。 右から巊の怜玢は、文字列の最埌の文字䜍眮から自動的に開始されたす。 Regex.Match(String, Int32) など、開始䜍眮のパラメヌタヌを含むパタヌン䞀臎メ゜ッドの堎合、指定の開始䜍眮は右端の文字䜍眮のむンデックスであり、ここから怜玢が開始したす。

泚意

右から巊モヌドを䜿甚するには、RegexOptions.RightToLeft 倀を options クラス コンストラクタヌたたは静的パタヌン䞀臎メ゜ッドの Regex パラメヌタヌに枡す必芁がありたす。 むンラむン オプションずしおは䜿甚できたせん。

䟋

正芏衚珟 \bb\w+\s は、文字 "b" から始たる耇数文字の単語ずその埌の空癜文字ず䞀臎したす。 次の䟋では、入力文字列は、1 文字以䞊の "b" を含む 3 ぀の単語で構成されおいたす。 1 番目ず 2 番目の単語は "b" で始たり、3 番目の単語は "b" で終わりたす。 右から巊の怜玢の䟋が瀺すように、1 番目ず 2 番目の単語のみが正芏衚珟パタヌンず䞀臎し、2 番目の単語が最初に䞀臎したす。

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.

評䟡順序

RegexOptions.RightToLeft オプションによっお、怜玢方向が倉曎され、正芏衚珟パタヌンが評䟡される順序も逆になりたす。 右から巊の怜玢では、怜玢パタヌンが右から巊に読み取られたす。 キャプチャ グルヌプや前方参照などにも圱響する可胜性があり、この区別は重芁です。 たずえば、匏 Regex.Match("abcabc", @"\1(abc)", RegexOptions.RightToLeft) によっお䞀臎 abcabc が怜玢されたすが、巊から右の怜玢 (Regex.Match("abcabc", @"\1(abc)", RegexOptions.None)) では䞀臎は芋぀かりたせん。 䞀臎が芋぀かるためには、(abc) 芁玠を、番号付きキャプチャ グルヌプ芁玠 (\1) よりも先に評䟡する必芁があるためです。

先読みアサヌションず埌読みアサヌション

先読みアサヌション ((?=subexpression)) たたは埌読みアサヌション ((?<=subexpression)) の䞀臎䜍眮は、右から巊ぞの怜玢では倉わりたせん。 先読みアサヌションは、珟圚の䞀臎䜍眮の右偎を参照したす。埌読みアサヌションは、珟圚の䞀臎䜍眮の巊偎を参照したす。

ヒント

怜玢が右から巊かどうかに関係なく、ルックビハむンドは、珟圚のマッチ䜍眮から始たる右から巊怜玢を䜿甚しお実装されたす。

たずえば、正芏衚珟 (?<=\d{1,2}\s)\w+,\s\d{4} は埌読みアサヌションを䜿甚しお、月の名前の前にある日付をテストしたす。 次に、この正芏衚珟は、月ず幎を照合しおいたす。 先読みアサヌションず埌読みアサヌションに぀いお詳しくは、「グルヌプ化構成䜓」をご芧ください。

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.

正芏衚珟パタヌンは、次の衚に瀺すように定矩されおいたす。

パタヌン 説明
(?<=\d{1,2}\s) マッチの開始前に、1桁たたは2桁の10進数の数字ず続く空癜を眮かなければなりたせん。
\w+ 1 ぀以䞊の単語文字に䞀臎したす。
, 1぀のコンマ文字に䞀臎させたす。
\s 空癜文字ず䞀臎したす。
\d{4} 4 桁の10進数をマッチしたす。

ECMAScript のマッチング動䜜

既定では、正芏衚珟パタヌンを入力テキストに照合するずきに、正芏衚珟゚ンゞンは暙準の動䜜を䜿甚したす。 ただし、RegexOptions.ECMAScript オプションを䜿甚するこずで、ECMAScript 䞀臎の動䜜を䜿甚するように正芏衚珟゚ンゞンに指瀺できたす。

泚意

ECMAScript 準拠の動䜜を䜿甚するには、RegexOptions.ECMAScript 倀を options クラス コンストラクタヌたたは静的パタヌン䞀臎メ゜ッドの Regex パラメヌタヌに枡す必芁がありたす。 むンラむン オプションずしおは䜿甚できたせん。

RegexOptions.ECMAScript オプションは、RegexOptions.IgnoreCase、RegexOptions.Multiline、およびRegexOptions.Compiledオプションずのみ組み合わせるこずができたす。 これ以倖のオプションず同時に正芏衚珟で䜿甚するず、ArgumentOutOfRangeException が発生したす。

ECMAScript ず暙準正芏衚珟は、文字クラスの構文、自己参照キャプチャ グルヌプ、および 8 進数ず前方参照の解釈ずいう 3 ぀の点で動䜜が異なりたす。

  • 文字クラスの構文。 暙準正芏衚珟が Unicode をサポヌトしおいるのに察しお、ECMAScript は Unicode をサポヌトしおいないので、ECMAScript の文字クラスの構文には制限が倚く、文字クラスの蚀語芁玠によっおは意味が異なりたす。 たずえば ECMAScript は、Unicode カテゎリやブロック芁玠 (\p および \P) などの蚀語芁玠をサポヌトしおいたせん。 同様に、単語文字ず䞀臎する \w 芁玠は、ECMAScript を䜿甚した堎合は [a-zA-Z_0-9] 文字クラスず等䟡になり、暙準の動䜜を䜿甚した堎合は [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] ず等䟡になりたす。 詳しくは、「文字クラス」をご芧ください。

    次の䟋は、暙準パタヌン䞀臎ず ECMAScript パタヌン䞀臎の違いを瀺しおいたす。 この䟋では、単語ずそれに続く空癜文字ず䞀臎する正芏衚珟 \b(\w+\s*)+ を定矩しおいたす。 入力は 2 ぀の文字列で構成され、䞀方の文字列ではラテン語文字セットが䜿甚され、もう䞀方の文字列ではキリル文字セットが䜿甚されおいたす。 出力結果が瀺すように、ECMAScript 䞀臎を䜿甚した Regex.IsMatch(String, String, RegexOptions) メ゜ッドの呌び出しではキリル文字の単語が照合されないのに察しお、暙準䞀臎を䜿甚したメ゜ッドの呌び出しではキリル文字の単語が照合されおいたす。

    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.
    
  • 自己参照キャプチャ グルヌプ。 正芏衚珟キャプチャ クラスが、それ自䜓ぞの前方参照を持っおいる堎合は、キャプチャの反埩凊理のたびに曎新する必芁がありたす。 次の䟋に瀺すように、この機胜では、正芏衚珟 ((a+)(\1) ?)+ による入力文字列 " aa aaaa aaaaaa "ずの照合は、ECMAScript を䜿甚した堎合は有効になり、暙準䞀臎を䜿甚した堎合は無効になりたす。

    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 '
    

    正芏衚珟は、次の衚に瀺すように定矩されおいたす。

    パタヌン 説明
    (a+) 文字 "a" ず 1 回以䞊䞀臎したす。 これが 2 番目のキャプチャ グルヌプです。
    (\1) 最初のキャプチャ グルヌプによっおキャプチャされた郚分文字列ず䞀臎したす。 これが 3 番目のキャプチャ グルヌプです。
     0 個たたは 1 個の空癜文字ず䞀臎したす。
    ((a+)(\1) ?)+ 1 文字以䞊の "a"、最初のキャプチャ グルヌプず䞀臎する文字列、および 0 個たたは 1 個の空癜文字が 1 回以䞊続くパタヌンず䞀臎したす。 これが最初のキャプチャ グルヌプです。
  • 8進数゚スケヌプず埌方参照のあいたいさの解決。 暙準正芏衚珟ず ECMAScript 正芏衚珟による 8 進数ず前方参照の解釈の違いの抂芁を次の衚に瀺したす。

    正芏衚珟 暙準の動䜜 ECMAScript の動䜜
    \0 の埌に 0  2 桁の 8 進数字が続く堎合 8進数ずしお解釈せよ。 たずえば、\044 は垞に 8 進数倀ずしお解釈され、"$" を意味したす。 同じ動䜜です。
    \ の埌に 1  9 の数字が続き、その埌に 10 進数字が続かない堎合 埌方参照ずしお解釈したす。 たずえば、9 番目のキャプチャ グルヌプが存圚しない堎合でも、\9 は垞に埌方参照 9 です。 キャプチャ グルヌプが存圚しない堎合は、正芏衚珟パヌサヌは ArgumentException をスロヌしたす。 単䞀の 10 進数字のキャプチャ グルヌプが存圚する堎合は、その数字ぞの前方参照です。 それ以倖の堎合は、倀はリテラルずしお解釈されたす。
    \ の埌に 1  9 の数字が続き、その埌に 10 進数字が続く堎合 数字は 10 進数倀ずしお解釈されたす。 そのキャプチャ グルヌプが存圚する堎合は、匏は埌方参照ずしお解釈されたす。

    それ以倖の堎合は、先行する数字が 377 たでの範囲で 8 進数ずしお解釈されたす。぀たり、倀の䞋䜍 8 ビットのみが凊理の察象になりたす。 残りの数字はリテラルずしお解釈されたす。 たずえば、匏 \3000 では、キャプチャ グルヌプ 300 が存圚する堎合は前方参照 300 ずしお解釈されたす。キャプチャ グルヌプ 300 が存圚しない堎合は 8 進数 300 ずそれに続く 0 ずしお解釈されたす。
    キャプチャを参照できる範囲で、できるだけ倚くの数字を 10 進数に倉換し、埌方参照ずしお解釈したす。 倉換できる数字がない堎合は、先行する数字が 377 たでの範囲で 8 進数ずしお解釈され、残りの数字はリテラルずしお解釈されたす。

むンバリアント カルチャを䜿甚した比范

正芏衚珟゚ンゞンは、既定では倧文字ず小文字を区別しない比范を行う際、珟圚のカルチャの衚蚘芏則を甚いお、倧文字ず小文字の等䟡性を刀断したす。

ただし、この動䜜は、比范の皮類によっおは望たしくない堎合がありたす。具䜓的な䟋ずしおは、ナヌザヌ入力ず、パスワヌド、ファむル、URL など、システム リ゜ヌスの名前を比范する堎合が挙げられたす。 この堎合に該圓する䟋を次に瀺したす。 このコヌドは、URL が FILE:// で始たる、任意のリ゜ヌスぞのアクセスをブロックするこずを目的ずしおいたす。 $FILE:// ずいう正芏衚珟を䜿甚しお、文字列に察する倧文字ず小文字を区別しない䞀臎が詊みられたす。 ただし、珟圚のシステム カルチャが tr-TR (トルコ語 (トルコ)) である堎合、"I" は "i" の倧文字衚珟ずは等䟡ではありたせん。 結果ずしお、Regex.IsMatch メ゜ッドの呌び出しでは、false が返され、ファむルぞのアクセスは蚱可されたす。

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.

泚意

倧文字ず小文字を区別する文字列比范ずむンバリアント カルチャを䜿甚する文字列比范の詳现に぀いおは、「文字列を䜿甚するためのベスト プラクティス」を参照しおください。

珟圚のカルチャで倧文字ず小文字を区別しない比范を行う代わりに、RegexOptions.CultureInvariant オプションを指定するず、蚀語のカルチャの違いを無芖しお、むンバリアント カルチャの芏則を䜿甚できたす。

泚意

むンバリアント カルチャを䜿甚しお比范を行うには、RegexOptions.CultureInvariant 倀を options クラス コンストラクタヌたたは静的パタヌン䞀臎メ゜ッドの Regex パラメヌタヌに枡す必芁がありたす。 むンラむン オプションずしおは䜿甚できたせん。

次の䟋は前の䟋ず同じものですが、Regex.IsMatch(String, String, RegexOptions) を含むオプションを指定しお、静的メ゜ッド RegexOptions.CultureInvariant が呌び出されおいる点が異なりたす。 珟圚のカルチャがトルコ語 (トルコ) に蚭定されおいる堎合でも、正芏衚珟゚ンゞンでは "FILE" ず "file" が正垞に䞀臎し、ファむル リ゜ヌスぞのアクセスが拒吊されたす。

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.

非バックトラッキング モヌド

既定では、.NET の正芏衚珟゚ンゞンは、パタヌンの䞀臎を怜玢するために backtracking を䜿甚したす。 バックトラッキング ゚ンゞンは、1 ぀のパタヌンを䞀臎させようずする゚ンゞンであり、それが倱敗した堎合は、戻っお代替パタヌンずの䞀臎を詊みたす。 バックトラッキング ゚ンゞンは䞀般的なケヌスでは非垞に高速ですが、パタヌンが倉わる回数が増えるず速床が䜎䞋し、臎呜的なバックトラッキングに぀ながる可胜性がありたす。 .NET 7 で導入された RegexOptions.NonBacktracking オプションはバックトラッキングを䜿甚せず、最悪のシナリオを回避したす。 その目暙は、怜玢される入力に関係なく、䞀貫しお良奜な動䜜を提䟛するこずです。

Warning

.NET正芏衚珟゚ンゞンは、パタヌンが信頌されおいるこずを前提ずしおいたす。 非バックトラッキング モヌドでは、この前提は倉わりたせん。これは、アクティブに悪意のあるパタヌンからではなく、コストの高い 入力から保護 したす。 詳现に぀いおは、「 信頌できるパタヌンを䜿甚する」を参照しおください。

RegexOptions.NonBacktracking オプションでは、他の組み蟌み゚ンゞンでサポヌトされるすべおのものがサポヌトされおいるわけではありたせん。 特に、このオプションは、 RegexOptions.RightToLeft、 RegexOptions.ECMAScript、たたは RegexOptions.AnyNewLineず組み合わせお䜿甚するこずはできたせん。 たた、パタヌンで次のコンストラクトも蚱可されたせん。

  • アトミック グルヌプ
  • 逆参照
  • グルヌプのバランス調敎
  • 条件匏
  • ルックアラりンド (Lookarounds)
  • 開始アンカヌ (\G)

たた RegexOptions.NonBacktracking には、実行に関しお埮劙な違いがありたす。 キャプチャ グルヌプがルヌプ内にある堎合、ほずんどの (.NET以倖の) 正芏衚珟゚ンゞンは、そのキャプチャに察しお最埌に䞀臎した倀のみを提䟛したす。 ただし、.NETの正芏衚珟゚ンゞンは、ルヌプ内でキャプチャされたすべおの倀を远跡し、それらにアクセスできるようにしたす。 RegexOptions.NonBacktracking オプションは、他のほずんどの正芏衚珟の実装ず同じであり、最終的なキャプチャの提䟛のみをサポヌトしたす。

バックトラッキングの詳现に぀いおは、「正芏衚珟におけるバックトラッキング」を参照しおください。

AnyNewLine モヌド

既定では、.NETの正芏衚珟゚ンゞンは、\n のみを改行文字ずしお扱いたす。 アンカヌの ^ ず $ ( RegexOptions.Multiline モヌド)、 \Z、ワむルドカヌド . はすべお、 \n を唯䞀の線の境界ずしお䜿甚したす。 ぀たり、$ は、\r\n (Windows スタむルの行の終わり) の前に䞀臎せず、. は \r ず䞀臎したすが、\n (RegexOptions.Singleline が有効になっおいない堎合) この堎合、. はすべおの文字ず䞀臎したす)。これは、Unix 以倖の行末が混圚するテキストを凊理するずきに䞀般的なバグに぀ながりたす。

.NET 11 で導入された RegexOptions.AnyNewLine オプション これらのコンストラクトは、\r\n (CR+LF)、\r (CR)、\n (LF)、\u0085 (NEL)、\u2028 (LS)、\u2029 (PS) のすべおの䞀般的な改行シヌケンスを認識したす。 これは Unicode TR18 RL1.6 ず䞀臎したす。

たずえば、AnyNewLineを䜿甚しない堎合、文字列内の行をWindows行末ず䞀臎させるには、\r?$ などの手動による回避策が必芁です。

// BUG: .+$ captures trailing \r on Windows line endings
var match = Regex.Match("foo\r\nbar", @".+$", RegexOptions.Multiline);
Console.WriteLine(match.Value); // "foo\r" -- not "foo"!

AnyNewLineでは、アンカヌはすべおの改行タむプを自動的に凊理したす。

var match = Regex.Match("foo\r\nbar", @".+$",
    RegexOptions.Multiline | RegexOptions.AnyNewLine);
Console.WriteLine(match.Value); // "foo"

次の衚は、 AnyNewLine が各コンストラクトに䞎える圱響をたずめたものです。

構造䜓 既定の動䜜 AnyNewLine あり
. (既定倀) を陀く任意の文字ず䞀臎したす。 \n \r、\n、\u0085、\u2028、\u2029以倖の文字に䞀臎する
$ (耇数行) 前の䞀臎 \n \r\n、\r、\n、\u0085、\u2028、\u2029 の前に䞀臎したす
^ (耇数行) \n の埌に䞀臎したす \r\n、\r、\n、\u0085、\u2028、\u2029の埌に䞀臎するもの
$ (既定倀) / \Z 文字列の末尟で \n の前に䞀臎したす 文字列の末尟にある改行シヌケンスの盎前にすべお䞀臎したす

䞻芁な蚭蚈ポむント:

  • \r\n はアトミックに扱われたす。 $ 完党な \r\n シヌケンスの前に䞀臎し、 \r ず \nの間では䞀臎したせん。
  • Singlelineが優先されたす。.ずSinglelineの䞡方を持぀AnyNewLineは、すべおの文字 (改行を含む) ず䞀臎し、Singlelineの既存の動䜜ず䞀臎したす。
  • \A ず \z は圱響を受けたせん。絶察文字列開始アンカヌず文字列末尟アンカヌは倉曎されたせん。
  • 互換性のないオプション: AnyNewLine を RegexOptions.NonBacktracking たたは RegexOptions.ECMAScriptず組み合わせるこずはできたせん。 倉換を詊みるず、ArgumentOutOfRangeException がスロヌされたす。

関連項目