添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

替換元素是只能在替換模式內辨識的語言元素。 它們會使用正則表示式模式來定義要取代輸入字串中相符文字的所有或部分文字。 取代模式可以包含一個或多個替換項以及文字字元。 具有 Regex.Replace 參數的 replacement 方法和 Match.Result 方法的多載會提供替代模式。 方法會將相符的模式替換為由 replacement 參數定義的模式。

.NET 定義了下表列出的替代元素。

替代元素和取代模式

替代是替代模式中唯一可辨識的特殊建構。 不支援其他正則表達式語言元素,包括字元跳脫和匹配任何字元的句點( . )。 同樣地,替代語言元素只會在取代模式中辨識,而且在正則表示式模式中永遠不會有效。

唯一可以出現在正則表達式模式或替代中的字元是 $ 字元,雖然它在每個內容中都有不同的意義。 在正則表達式模式中, $ 是符合字串結尾的錨點。 在取代模式中, $ 表示替代的開頭。

如果您需要正則表示式中類似替換模式的功能,請使用反向引用。 如需反向參考的詳細資訊,請參閱 Backreference 建構

替換編號的群組

number language 元素包含取代字串中與 number 擷取群組相符的最後一個子字串,其中 number 是擷取群組的索引。 例如,取代模式 $1 表示相符的子字串將由第一個擷取的群組取代。 如需編號擷取群組的詳細資訊,請參閱 群組建構

下列 $ 所有數字都會解譯為屬於 數位 群組。 如果這不是您的意圖,您可以改為替代具名群組。 例如,您可以使用取代字串 ${1}1 來取代 $11 ,將 ${1}1 定義為第一個擷取群組的值以及數字 "1"。 如需詳細資訊,請參閱 取代具名群組

使用 (?< 名稱 >) 語法未明確指派名稱的擷取群組,會從左到右從一開始編號。 具名群組也會從左至右編號,從一個大於最後一個未命名群組的索引開始。 例如,在正則表達式 (\w)(?<digit>\d) 中,具名群組的 digit 索引是 2。

如果 number 未指定正則表示式模式中定義的有效擷取群組, $ 則 number 會被解讀為用來取代每個相符項目的字面字元序列。

下列範例會 $ 使用 數字 替代來移除十進位值上的貨幣符號。 它會移除貨幣值開頭或結尾找到的貨幣符號,並辨識兩個最常見的小數分隔符 (“” 和 “,”)。

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}* 的定義如下表所示。

name} 語言專案會取代名稱擷取群組所比對的最後一個子字串,其中name(?<語言專案所>)定義的擷取群組名稱。 如需具名擷取群組的詳細資訊,請參閱 群組建構

如果 name 未指定正規表示式模式中定義的有效具名擷取群組,但包含數位, ${則會將名稱} 解譯為編號群組。

如果 name 未指定有效的具名擷取群組,也沒有指定正則表達式模式中定義的有效編號擷取群組,${name} 會被解釋為用來取代每個匹配項的字面字元序列。

下列範例中${使用name}替代來將貨幣符號從十進位值中去除。 它會移除貨幣值開頭或結尾找到的貨幣符號,並辨識兩個最常見的小數分隔符 (“” 和 “,”)。

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}* 的定義如下表所示。

$$ 子串替換會在結果中插入字面上的「$」字元。

下列範例使用 NumberFormatInfo 物件來判斷目前文化特性的貨幣符號及其在貨幣字串中的位置。 然後,它會動態建置正則表達式模式和取代模式。 如果此範例是在目前文化特性為 en-US的電腦上執行,則會產生正規表示式模式 \b(\d+)(\.(\d+))? 和取代模式 $$ $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))
    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+))? 的定義如下表所示。

替換整個相符項目

替代 $& 專案會在取代字串中包含整個相符專案。 通常,它會用來將子字串新增至相符字串的開頭或結尾。 例如,在取代模式中,($&) 會在每個匹配項的開頭和結尾添加括號。 如果沒有匹配,則 $& 替代沒有任何作用。

下列範例使用了$&替代方法,在儲存在字串陣列中的書名開頭和結尾加上引號。

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))
    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?)+$ 的定義如下表所示。

取代模式會將 "$&" 常值引號新增至每個相符項目的開頭和結尾。

取代比對前的文字

替代專案會將 $` 比對字串取代為比對之前的整個輸入字串。 也就是說,它會將輸入字串重複至匹配的部分,同時移除匹配的文字。 在結果字串中,符合文字後面的任何文字都未變更。 如果輸入字串中有多個符合項目,取代文字會來自於原始輸入字串,而不是從之前符合項目取代過的字串。 此範例提供示例。如果沒有相符,則 $` 替代沒有任何作用。

下列範例會使用正則表達式模式 \d+ 來比對輸入字串中的一或多個十進位數序列。 取代字串 $` 會將這些數字取代為相符內容之前的文字。

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)
        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" 包含五個相符項目。 下表說明如何使用 $` 替換會使正則表達式引擎取代輸入字串中的每個匹配項目。 插入的文字會在結果數據行中以粗體顯示。

匹配前的字串

匹配之後替換文字

替代 $' 將相符字串取代為比對後的整個輸入字串。 也就是說,它會在移除相符的文字時複製比對后的輸入字串。 結果字串中相符文字前面的任何文字都未變更。 如果沒有匹配,則 $' 替代沒有任何作用。

下列範例會使用正則表達式模式 \d+ 來比對輸入字串中的一或多個十進位數序列。 替換字串 $' 會將這些數字替換為相符文字後面的文字。

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)
        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" 包含五個相符項目。 下表說明如何使用 $' 替換會使正則表達式引擎取代輸入字串中的每個匹配項目。 插入的文字會在結果數據行中以粗體顯示。

匹配后的字串 $+ 會將相符的字串替換為最後擷取的群組。 如果沒有擷取的群組,或最後一個擷取群組的值是 String.Empty,則 $+ 替代沒有任何作用。

下列範例會識別字串中的重複單字,並使用 $+ 替代來取代單一出現的單字。 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 的定義如下表所示。

$_ 替代將整個輸入字串替換掉相符的字串。 也就是說,它會移除相符的文字,並將整個字串(包括相符的文字)取代原本的文字。

下列範例會比對輸入字串中的一或多個十進位數。 它會使用 $_ 替換機制來用整個輸入的字串取代它們。

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" 包含兩個相符項目。 下表說明如何使用 $_ 替換會使正則表達式引擎取代輸入字串中的每個匹配項目。 插入的文字會在結果數據行中以粗體顯示。