正则表达式中的替代

替换是只能在替换模式中识别的语言元素。 它们使用正则表达式模式定义要替换输入字符串中匹配文本的全部或部分文本。 替换模式可以包含一个或多个替换项以及字面字符。 提供替换模式以将拥有 Regex.Replace 参数的 replacement 方法重载至 Match.Result 方法。 这些方法将匹配的模式替换为参数定义的 replacement 模式。

.NET 定义下表中列出的替换元素。

替换 DESCRIPTION
$ 数量 包括替换字符串中的由 number标识的捕获组所匹配的最后一个子字符串,其中 number 是一个十进制值。 有关详细信息,请参阅 替换编号组
${ name } 包括替换字符串中由 (?<name> ) 指定的命名组所匹配的最后一个子字符串。 有关详细信息,请参阅 替换命名组
$$ 包括替换字符串中的单个“$”文本。 有关详细信息,请参阅 替换“$”符号
$& 包括替换字符串中整个匹配项的副本。 有关详细信息,请参阅 替换整个匹配项
$` 包括替换字符串中的匹配项前的输入字符串的所有文本。 有关详细信息,请参阅 替换匹配项前的文本
$' 包括替换字符串中的匹配项后的输入字符串的所有文本。 有关详细信息,请参阅 替换匹配后的文本
$+ 包括在替换字符串中捕获的最后一个组。 有关详细信息,请参阅 替换最后捕获的组
$_ 在替换字符串中包含整个输入字符串。 有关详细信息,请参阅 替换整个输入字符串

替换元素和替换模式

在替换模式中,替换是唯一被识别的特别结构。 与任何字符匹配的其他正则表达式语言元素(包括字符转义和句点 (.))均不受支持。 同样,替换语言元素仅在替换模式中被识别,并且永远不会在正则表达式模式中有效。

唯一可以出现在正则表达式模式或替换中的字符是 $ 字符,尽管它在每个上下文中都有不同的含义。 在正则表达式模式中, $ 是与字符串末尾匹配的定位点。 在替换模式中, $ 指示替换的开头。

注释

对于类似于正则表达式中的替换模式的功能,请使用反向引用。 有关反向引用的详细信息,请参阅 Backreference 构造

替换已编号的组

$ 数字语言元素包括由替换字符串中的数字捕获组匹配的最后一个子字符串,其中数字是捕获组的索引。 例如,替换模式 $1 指示匹配的子字符串将被第一个捕获的组替换。 有关编号捕获组的详细信息,请参阅 分组构造

后面的 $ 所有数字都解释为属于 数字 组。 如果这不是你想要的结果,可改为替换命名组。 例如,可以使用替换字符串而不是${1}1将替换字符串$11定义为第一个捕获组的值以及数字“1”。 有关详细信息,请参阅 替换命名组

没有使用 (?<name>) 语法显式分配的名称的捕获组从左到右进行编号(从 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}* 的定义如下表所示。

图案 DESCRIPTION
\p{Sc}* 与零个或多个货币符号字符匹配。
\s? 匹配零个或一个空格字符。
\d+ 匹配一个或多个十进制数字。
[.,]? 与零个或一个句点或逗号匹配。
\d* 匹配零个或多个十进制数字。
(\s?\d+[.,]?\d*) 匹配空白,后跟一个或多个十进制数,再后跟零个或一个句点或逗号,后跟零个或多个十进制数。 这是第一个捕获组。 由于替换模式是 $1,调用Regex.Replace方法时,整个匹配的子字符串会被替换为该捕获组。

替换命名组

${ 名称}语言元素替换名称捕获组匹配的最后一个子字符串,其中名称(?<语言元素定义的>)捕获组的名称。 有关命名捕获组的详细信息,请参阅 分组构造

如果 名称 未指定在正则表达式模式中定义的有效命名捕获组,但由数字组成, ${则将名称} 解释为编号组。

如果 名称 既未指定有效的命名捕获组,也未指定正则表达式模式中定义的有效编号捕获组, ${则将名称} 解释为用于替换每个匹配项的文本字符序列。

以下示例使用 ${名称} 替换从十进制值中去除货币符号。 它删除货币值开头或末尾找到的货币符号,并识别两个最常见的小数分隔符(“.”和“,”)。

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

图案 DESCRIPTION
\p{Sc}* 与零个或多个货币符号字符匹配。
\s? 匹配零个或一个空格字符。
\d+ 匹配一个或多个十进制数字。
[.,]? 与零个或一个句点或逗号匹配。
\d* 匹配零个或多个十进制数字。
(?<amount>\s?\d[.,]?\d*) 匹配空白,后跟一个或多个十进制数,再后跟零个或一个句点或逗号,后跟零个或多个十进制数。 这是名为 amount的捕获组。 由于替换模式是 ${amount},调用Regex.Replace方法时,整个匹配的子字符串会被替换为该捕获组。

替换“$”字符

$$ 替换将在替换的字符串中插入文本“$”字符。

下面的示例使用 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))
        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+))? 的定义如下表所示。

图案 DESCRIPTION
\b 从字边界开始进行匹配。
(\d+) 匹配一个或多个十进制数字。 这是第一个捕获组。
\. 与句点(小数点分隔符)匹配。
(\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))
        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?)+$ 的定义如下表所示。

图案 DESCRIPTION
^ 在输入字符串的开头开始匹配。
(\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)
        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" 包含五个匹配项。 下表展示了 $` 替换机制如何使正则表达式引擎替换输入字符串中的每个匹配项。 插入的文本在结果列中以粗体显示。

匹配 位置 匹配项前的字符串 结果字符串
1 2 机 管 局 aaaabb2cc3dd4ee5
2 5 aa1bb aaaabbaa1bbcc3dd4ee5
3 8 aa1bb2cc aaaabbaa1bbcc aa1bb2ccdd4ee5
4 11 aa1bb2cc3dd aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddee5
5 14 aa1bb2cc3dd4ee aaaabbaa1bbccaa1bb2ccdaa1bb2cc3ddeeaa1bb2cc3dd4ee

替换匹配项后的文本

$' 替换将匹配的字符串替换为匹配项后的整个输入字符串。 即,它将在删除匹配的文本时重复匹配项后的输入字符串。 匹配文本前面的任何文本在结果字符串中保持不变。 如果没有匹配项,则 $' 替换不起作用。

以下示例使用正则表达式模式 \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)
        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" 包含五个匹配项。 下表展示了 $' 替换机制如何使正则表达式引擎替换输入字符串中的每个匹配项。 插入的文本在结果列中以粗体显示。

匹配 位置 匹配项后的字符串 结果字符串
1 2 bb2cc3dd4ee5 aabb2cc3dd4ee5bb2cc3dd4ee5
2 5 cc3dd4ee5 aabb2cc3dd4ee5bbcc3dd4ee5cc3dd4ee5
3 8 dd4ee5 aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5dd4ee5
4 11 ee5 aabb2cc3dd4ee5bbcc3dd4ee5ccd4ee5ddee5 ee5
5 14 String.Empty aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee5ee

替换最后捕获的组

$+ 替换将匹配的字符串替换为最后捕获的组。 如果没有捕获的组,或者最后一个捕获组的值是 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 的定义如下表所示。

图案 DESCRIPTION
\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" 包含两个匹配项。 下表展示了 $_ 替换机制如何使正则表达式引擎替换输入字符串中的每个匹配项。 插入的文本在结果列中以粗体显示。

匹配 位置 匹配 结果字符串
1 3 123 ABCABC123DEF456DEF456
2 5 456 ABCABC123DEF456DEFABC123DEF456

另请参阅