次の方法で共有


正規表現での置換

置換は、置換パターン内でのみ認識される言語要素です。 正規表現パターンを使用して、入力文字列内の一致したテキストを置き換えるテキストのすべてまたは一部を定義します。 置換パターンは、1 つ以上の置換とリテラル文字で構成できます。 置換パターンは、replacement パラメーターを持つRegex.Replace メソッドのオーバーロードと、Match.Result メソッドに提供されます。 メソッドは、一致したパターンを、 replacement パラメーターで定義されたパターンに置き換えます。

.NET では、次の表に示す置換要素を定義します。

代替 説明
$ 置換文字列に、数値で識別されるキャプチャ グループで一致する最後の部分文字列 ( 数値 は 10 進値) が含まれます。 詳細については、「番号付 きグループの置換」を参照してください。
${ name } 置換文字列に、 (?<name> ) によって指定された名前付きグループによって一致する最後の部分文字列が含まれます。 詳細については、「 名前付きグループの置換」を参照してください。
$$ 置換文字列に 1 つの "$" リテラルを含めます。 詳細については、「 $」記号の置換を参照してください。
$& 置換文字列に一致全体のコピーを含めます。 詳細については、「 一致全体の置換」を参照してください。
$` 置換文字列に一致する前の入力文字列のすべてのテキストが含まれます。 詳細については、「 一致する前のテキストの置換」を参照してください。
$' 置換文字列に一致した後の入力文字列のすべてのテキストが含まれます。 詳細については、「 一致後のテキストの置換」を参照してください。
$+ 置換文字列にキャプチャされた最後のグループが含まれます。 詳細については、「 最後にキャプチャされたグループの置換」を参照してください。
$_ 置換文字列に入力文字列全体を含めます。 詳細については、「 入力文字列全体の置換」を参照してください

置換要素と置換パターン

置換は、置換パターンで認識される唯一の特殊なコンストラクトです。 文字エスケープや、任意の文字に一致するピリオド (.) など、他の正規表現言語要素はサポートされていません。 同様に、置換言語要素は置換パターンでのみ認識され、正規表現パターンでは有効ではありません。

正規表現パターンまたは置換で使用できる唯一の文字は $ 文字ですが、各コンテキストで異なる意味を持ちます。 正規表現パターンでは、 $ は文字列の末尾に一致するアンカーです。 置換パターンでは、 $ は置換の開始を示します。

正規表現内の置換パターンに似た機能の場合は、逆参照を使用します。 逆参照の詳細については、「逆 参照コンストラクト」を参照してください。

番号付きグループの置換

$ number language 要素には、置換文字列内の数値キャプチャ グループと一致する最後の部分文字列が含まれます。ここで、数値はキャプチャ グループのインデックスです。 たとえば、置換パターン $1 は、一致した部分文字列が最初にキャプチャされたグループに置き換えられることを示します。 番号付きキャプチャ グループの詳細については、「 グループ化コンストラクト」を参照してください。

$に続くすべての数字は、番号グループに属していると解釈されます。 これが意図ではない場合は、代わりに名前付きグループを置き換えることができます。 たとえば、$11の代わりに置換文字列${1}1を使用して、最初にキャプチャされたグループの値として置換文字列を数値 "1" と共に定義できます。 詳細については、「 名前付きグループの置換」を参照してください。

(?< name>)構文を使用して明示的に割り当てられない名前のキャプチャ グループには、左から右に番号が付けられます。 名前付きグループも左から右に番号付けされ、最後の名前のないグループのインデックスより 1 つ大きい番号から始まります。 たとえば、正規表現 (\w)(?<digit>\d)では、 digit 名前付きグループのインデックスは 2 です。

正規表現パターンで定義された有効なキャプチャ グループが 数値 で指定されていない場合、 $番号 は、各一致を置換するために使用されるリテラル文字シーケンスとして解釈されます。

次の例では、 $数値 の置換を使用して、通貨記号を 10 進値から取り除きます。 通貨値の先頭または末尾にある通貨記号を削除し、最も一般的な 2 つの小数点区切り記号 ("." と ",") を認識します。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*";
      string replacement = "$1";
      string input = "$16.32 12.19 £16.29 €18.29  €18,29";
      string result = Regex.Replace(input, pattern, replacement);
      Console.WriteLine(result);
   }
}
// The example displays the following output:
//       16.32 12.19 16.29 18.29  18,29
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"
        Dim replacement As String = "$1"
        Dim input As String = "$16.32 12.19 £16.29 €18.29  €18,29"
        Dim result As String = Regex.Replace(input, pattern, replacement)
        Console.WriteLine(result)
    End Sub
End Module
' The example displays the following output:
'       16.32 12.19 16.29 18.29  18,29

正規表現パターン \p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}* は、次の表に示すように定義されています。

パターン 説明
\p{Sc}* 0 個以上の通貨記号文字と一致します。
\s? 0 文字または 1 個の空白文字と一致します。
\d+ 1 個以上の 10 進数と一致します。
[.,]? 0 または 1 のピリオドまたはコンマに一致します。
\d* 0 個以上の 10 進数と一致します。
(\s?\d+[.,]?\d*) 空白の後に 1 桁以上の 10 進数、0 桁または 1 つのピリオドまたはコンマ、0 桁以上の 10 進数が続く数字と一致します。 これが最初のキャプチャ グループです。 置換パターンが $1されているため、 Regex.Replace メソッドの呼び出しにより、一致した部分文字列全体がこのキャプチャされたグループに置き換えられます。

名前付きグループの置き換え

${ name}言語要素は、名前キャプチャ グループと一致する最後の部分文字列を置き換えます。名前は、(?<name>) 言語要素によって定義されたキャプチャ グループの名前です。 名前付きキャプチャ グループの詳細については、「 グループ化コンストラクト」を参照してください。

name が正規表現パターンで定義されている有効な名前付きキャプチャ グループを指定せず、数字で構成されている場合、${name} は番号付きグループとして解釈されます。

name で、有効な名前付きキャプチャ グループも、正規表現パターンで定義されている有効な番号付きキャプチャ グループも指定されていない場合、${name} は、各一致を置き換えるために使用されるリテラル文字シーケンスとして解釈されます。

次の例では、 ${name} 置換を使用して、通貨記号を 10 進値から削除します。 通貨値の先頭または末尾にある通貨記号を削除し、最も一般的な 2 つの小数点区切り記号 ("." と ",") を認識します。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*";
      string replacement = "${amount}";
      string input = "$16.32 12.19 £16.29 €18.29  €18,29";
      string result = Regex.Replace(input, pattern, replacement);
      Console.WriteLine(result);
   }
}
// The example displays the following output:
//       16.32 12.19 16.29 18.29  18,29
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*"
        Dim replacement As String = "${amount}"
        Dim input As String = "$16.32 12.19 £16.29 €18.29  €18,29"
        Dim result As String = Regex.Replace(input, pattern, replacement)
        Console.WriteLine(result)
    End Sub
End Module
' The example displays the following output:
'       16.32 12.19 16.29 18.29  18,29

正規表現パターン \p{Sc}*(?<amount>\s?\d[.,]?\d*)\p{Sc}* は、次の表に示すように定義されています。

パターン 説明
\p{Sc}* 0 個以上の通貨記号文字と一致します。
\s? 0 文字または 1 個の空白文字と一致します。
\d+ 1 個以上の 10 進数と一致します。
[.,]? 0 または 1 のピリオドまたはコンマに一致します。
\d* 0 個以上の 10 進数と一致します。
(?<amount>\s?\d[.,]?\d*) 空白の後に 1 桁以上の 10 進数、0 桁または 1 つのピリオドまたはコンマ、0 桁以上の 10 進数が続きます。 これは、 amountという名前のキャプチャ グループです。 置換パターンが ${amount}されているため、 Regex.Replace メソッドの呼び出しにより、一致した部分文字列全体がこのキャプチャされたグループに置き換えられます。

"$" 文字の置換

$$置換では、置換された文字列にリテラル "$" 文字が挿入されます。

次の例では、 NumberFormatInfo オブジェクトを使用して、現在のカルチャの通貨記号とその通貨文字列での配置を決定します。 次に、正規表現パターンと置換パターンの両方を動的に構築します。 現在のカルチャが en-USされているコンピューターで例を実行すると、正規表現パターン \b(\d+)(\.(\d+))? と置換パターン $$ $1$2が生成されます。 置換パターンは、一致したテキストを通貨記号とスペースに置き換え、その後に 1 番目と 2 番目にキャプチャされたグループを置き換えます。

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Define array of decimal values.
      string[] values= { "16.35", "19.72", "1234", "0.99"};
      // Determine whether currency precedes (True) or follows (False) number.
      bool precedes = NumberFormatInfo.CurrentInfo.CurrencyPositivePattern % 2 == 0;
      // Get decimal separator.
      string cSeparator = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator;
      // Get currency symbol.
      string symbol = NumberFormatInfo.CurrentInfo.CurrencySymbol;
      // If symbol is a "$", add an extra "$".
      if (symbol == "$") symbol = "$$";

      // Define regular expression pattern and replacement string.
      string pattern = @"\b(\d+)(" + cSeparator + @"(\d+))?";
      string replacement = "$1$2";
      replacement = precedes ? symbol + " " + replacement : replacement + " " + symbol;
      foreach (string value in values)
         Console.WriteLine($"{value} --> {Regex.Replace(value, pattern, replacement)}");
   }
}
// The example displays the following output:
//       16.35 --> $ 16.35
//       19.72 --> $ 19.72
//       1234 --> $ 1234
//       0.99 --> $ 0.99
Imports System.Globalization
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        ' Define array of decimal values.
        Dim values() As String = {"16.35", "19.72", "1234", "0.99"}
        ' Determine whether currency precedes (True) or follows (False) number.
        Dim precedes As Boolean = (NumberFormatInfo.CurrentInfo.CurrencyPositivePattern Mod 2 = 0)
        ' Get decimal separator.
        Dim cSeparator As String = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator
        ' Get currency symbol.
        Dim symbol As String = NumberFormatInfo.CurrentInfo.CurrencySymbol
        ' If symbol is a "$", add an extra "$".
        If symbol = "$" Then symbol = "$$"

        ' Define regular expression pattern and replacement string.
        Dim pattern As String = "\b(\d+)(" + cSeparator + "(\d+))?"
        Dim replacement As String = "$1$2"
        replacement = If(precedes, symbol + " " + replacement, replacement + " " + symbol)
        For Each value In values
            Console.WriteLine("{0} --> {1}", value, Regex.Replace(value, pattern, replacement))
        Next
    End Sub
End Module
' The example displays the following output:
'       16.35 --> $ 16.35
'       19.72 --> $ 19.72
'       1234 --> $ 1234
'       0.99 --> $ 0.99

正規表現パターン \b(\d+)(\.(\d+))? は、次の表に示すように定義されています。

パターン 説明
\b 単語の境界の先頭で一致を開始します。
(\d+) 1 個以上の 10 進数と一致します。 これが最初のキャプチャ グループです。
\. ピリオド (小数点区切り記号) と一致します。
(\d+) 1 個以上の 10 進数と一致します。 これが 3 番目のキャプチャ グループです。
(\.(\d+))? ピリオドが 0 個または 1 回出現し、その後に 1 桁以上の 10 進数が続きます。 これが 2 番目のキャプチャ グループです。

マッチ全体を置き換え

$&置換には、置換文字列内の一致全体が含まれます。 多くの場合、一致する文字列の先頭または末尾に部分文字列を追加するために使用されます。 たとえば、 ($&) 置換パターンでは、各一致の先頭と末尾にかっこが追加されます。 一致するものがない場合、 $& 置換は無効になります。

次の例では、 $& 置換を使用して、文字列配列に格納されている書籍タイトルの先頭と末尾に引用符を追加します。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"^(\w+\s?)+$";
      string[] titles = { "A Tale of Two Cities",
                          "The Hound of the Baskervilles",
                          "The Protestant Ethic and the Spirit of Capitalism",
                          "The Origin of Species" };
      string replacement = "\"$&\"";
      foreach (string title in titles)
         Console.WriteLine(Regex.Replace(title, pattern, replacement));
   }
}
// The example displays the following output:
//       "A Tale of Two Cities"
//       "The Hound of the Baskervilles"
//       "The Protestant Ethic and the Spirit of Capitalism"
//       "The Origin of Species"
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "^(\w+\s?)+$"
        Dim titles() As String = {"A Tale of Two Cities", _
                                   "The Hound of the Baskervilles", _
                                   "The Protestant Ethic and the Spirit of Capitalism", _
                                   "The Origin of Species"}
        Dim replacement As String = """$&"""
        For Each title As String In titles
            Console.WriteLine(Regex.Replace(title, pattern, replacement))
        Next
    End Sub
End Module
' The example displays the following output:
'       "A Tale of Two Cities"
'       "The Hound of the Baskervilles"
'       "The Protestant Ethic and the Spirit of Capitalism"
'       "The Origin of Species"

正規表現パターン ^(\w+\s?)+$ は、次の表に示すように定義されています。

パターン 説明
^ 入力文字列の先頭で一致を開始します。
(\w+\s?)+ 1 つ以上の単語文字のパターンに一致し、その後に 0 文字または 1 つの空白文字が 1 回以上続きます。
$ 入力文字列の末尾と一致します。

"$&"置換パターンは、各一致の先頭と末尾にリテラル引用符を追加します。

一致する前にテキストを置き換え

$` 置換は、一致した文字列を、一致する前の入力文字列全体に置き換えます。 つまり、一致するテキストを削除しながら、入力文字列を一致まで複製します。 一致したテキストの後に続くテキストは、結果文字列内で変更されません。 入力文字列に複数の一致がある場合、置換テキストは、テキストが以前の一致に置き換えられた文字列からではなく、元の入力文字列から派生します。 (この例では、図を示します)。一致するものがない場合、 $` 置換は無効になります。

次の例では、正規表現パターン \d+ を使用して、入力文字列内の 1 桁以上の 10 進数のシーケンスを照合します。 置換文字列 $` は、これらの数字を一致の前のテキストに置き換えます。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "aa1bb2cc3dd4ee5";
      string pattern = @"\d+";
      string substitution = "$`";
      Console.WriteLine("Matches:");
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine($"   {match.Value} at position {match.Index}");

      Console.WriteLine($"Input string:  {input}");
      Console.WriteLine("Output string: " +
                        Regex.Replace(input, pattern, substitution));
   }
}
// The example displays the following output:
//    Matches:
//       1 at position 2
//       2 at position 5
//       3 at position 8
//       4 at position 11
//       5 at position 14
//    Input string:  aa1bb2cc3dd4ee5
//    Output string: aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddeeaa1bb2cc3dd4ee
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "aa1bb2cc3dd4ee5"
        Dim pattern As String = "\d+"
        Dim substitution As String = "$`"
        Console.WriteLine("Matches:")
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("   {0} at position {1}", match.Value, match.Index)
        Next
        Console.WriteLine("Input string:  {0}", input)
        Console.WriteLine("Output string: " + _
                          Regex.Replace(input, pattern, substitution))
    End Sub
End Module
' The example displays the following output:
'    Matches:
'       1 at position 2
'       2 at position 5
'       3 at position 8
'       4 at position 11
'       5 at position 14
'    Input string:  aa1bb2cc3dd4ee5
'    Output string: aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddeeaa1bb2cc3dd4ee

この例では、入力文字列 "aa1bb2cc3dd4ee5" に 5 つの一致が含まれています。 次の表は、 $` 置換によって正規表現エンジンが入力文字列内の各一致を置き換える方法を示しています。 挿入されたテキストは、結果列に太字で表示されます。

試合 職位 一致前の文字列 結果文字列
1 2 aa aaaabb2cc3dd4ee5
2 5 aa1bb aaaabbaa1bbcc3dd4ee5
3 8 aa1bb2cc aaaabbaa1bbccaa1bb2ccdd4ee5
4 11 aa1bb2cc3dd aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddee5
5 14 aa1bb2cc3dd4ee aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddeeaa1bb2cc3dd4ee

一致した後のテキストの置換

$'置換は、一致した文字列を、一致した後の入力文字列全体に置き換えます。 つまり、一致したテキストを削除しながら、一致した後に入力文字列を複製します。 一致したテキストの前にあるテキストは、結果文字列内で変更されません。 一致するものがない場合、 $' 置換は無効になります。

次の例では、正規表現パターン \d+ を使用して、入力文字列内の 1 桁以上の 10 進数のシーケンスを照合します。 置換文字列 $' は、これらの数字を一致に続くテキストに置き換えます。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "aa1bb2cc3dd4ee5";
      string pattern = @"\d+";
      string substitution = "$'";
      Console.WriteLine("Matches:");
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine($"   {match.Value} at position {match.Index}");
      Console.WriteLine($"Input string:  {input}");
      Console.WriteLine("Output string: " +
                        Regex.Replace(input, pattern, substitution));
   }
}
// The example displays the following output:
//    Matches:
//       1 at position 2
//       2 at position 5
//       3 at position 8
//       4 at position 11
//       5 at position 14
//    Input string:  aa1bb2cc3dd4ee5
//    Output string: aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "aa1bb2cc3dd4ee5"
        Dim pattern As String = "\d+"
        Dim substitution As String = "$'"
        Console.WriteLine("Matches:")
        For Each match As Match In Regex.Matches(input, pattern)
            Console.WriteLine("   {0} at position {1}", match.Value, match.Index)
        Next
        Console.WriteLine("Input string:  {0}", input)
        Console.WriteLine("Output string: " + _
                          Regex.Replace(input, pattern, substitution))
    End Sub
End Module
' The example displays the following output:
'    Matches:
'       1 at position 2
'       2 at position 5
'       3 at position 8
'       4 at position 11
'       5 at position 14
'    Input string:  aa1bb2cc3dd4ee5
'    Output string: aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee

この例では、入力文字列 "aa1bb2cc3dd4ee5" に 5 つの一致が含まれています。 次の表は、 $' 置換によって正規表現エンジンが入力文字列内の各一致を置き換える方法を示しています。 挿入されたテキストは、結果列に太字で表示されます。

試合 職位 一致後の文字列 結果文字列
1 2 bb2cc3dd4ee5 aabb2cc3dd4ee5bb2cc3dd4ee5
2 5 cc3dd4ee5 aabb2cc3dd4ee5bbcc3dd4ee5cc3dd4ee5
3 8 dd4ee5 aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5dd4ee5
4 11 ee5 aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee5
5 14 String.Empty aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee

最後にキャプチャされたグループの置き換え

$+置換は、一致した文字列を最後にキャプチャしたグループに置き換えます。 キャプチャされたグループがない場合、または最後にキャプチャしたグループの値が String.Empty場合、 $+ の置換は無効になります。

次の例では、文字列内の重複する単語を識別し、 $+ 置換を使用して単語を 1 回出現する単語に置き換えます。 RegexOptions.IgnoreCaseオプションは、大文字と小文字が異なるが同じ単語が重複していると見なされるようにするために使用されます。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\w+)\s\1\b";
      string substitution = "$+";
      string input = "The the dog jumped over the fence fence.";
      Console.WriteLine(Regex.Replace(input, pattern, substitution,
                        RegexOptions.IgnoreCase));
   }
}
// The example displays the following output:
//      The dog jumped over the fence.
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim pattern As String = "\b(\w+)\s\1\b"
        Dim substitution As String = "$+"
        Dim input As String = "The the dog jumped over the fence fence."
        Console.WriteLine(Regex.Replace(input, pattern, substitution, _
                                        RegexOptions.IgnoreCase))
    End Sub
End Module
' The example displays the following output:
'      The dog jumped over the fence.

正規表現パターン \b(\w+)\s\1\b は、次の表に示すように定義されています。

パターン 説明
\b ワード境界から照合を開始します。
(\w+) 1 つ以上の単語文字に一致します。 これが最初のキャプチャ グループです。
\s 空白文字と一致します。
\1 キャプチャされた最初のグループと一致します。
\b ワード境界で照合を終了します。

入力文字列全体の置換

$_置換は、一致した文字列を入力文字列全体に置き換えます。 つまり、一致したテキストを削除し、一致したテキストを含む文字列全体に置き換えます。

次の例では、入力文字列内の 1 桁以上の 10 進数と一致します。 $_置換を使用して、入力文字列全体に置き換えます。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "ABC123DEF456";
      string pattern = @"\d+";
      string substitution = "$_";
      Console.WriteLine($"Original string:          {input}");
      Console.WriteLine($"String with substitution: {Regex.Replace(input, pattern, substitution)}");
   }
}
// The example displays the following output:
//       Original string:          ABC123DEF456
//       String with substitution: ABCABC123DEF456DEFABC123DEF456
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim input As String = "ABC123DEF456"
        Dim pattern As String = "\d+"
        Dim substitution As String = "$_"
        Console.WriteLine("Original string:          {0}", input)
        Console.WriteLine("String with substitution: {0}", _
                          Regex.Replace(input, pattern, substitution))
    End Sub
End Module
' The example displays the following output:
'       Original string:          ABC123DEF456
'       String with substitution: ABCABC123DEF456DEFABC123DEF456

この例では、入力文字列 "ABC123DEF456" に 2 つの一致が含まれています。 次の表は、 $_ 置換によって正規表現エンジンが入力文字列内の各一致を置き換える方法を示しています。 挿入されたテキストは、結果列に太字で表示されます。

試合 職位 試合 結果文字列
1 3 123 ABCABC123DEF456DEF456
2 5 456 ABCABC123DEF456DEFABC123DEF456

こちらも参照ください