正则表达式中的替代Substitutions in Regular Expressions

替换是只能在替换模式中识别的语言元素。Substitutions are language elements that are recognized only within replacement patterns. 它们使用正则表达式模式定义全部或部分用于替换输入字符串中的匹配文本的文本。They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. 替换模式可以包含一个或多个替换以及本文字符。The replacement pattern can consist of one or more substitutions along with literal characters. 提供替换模式以将拥有 Regex.Replace 参数的 replacement 方法重载至 Match.Result 方法。Replacement patterns are provided to overloads of the Regex.Replace method that have a replacement parameter and to the Match.Result method. 该方法将匹配的模式替换为 replacement 参数定义的模式。The methods replace the matched pattern with the pattern that is defined by the replacement parameter.

.NET Framework 定义下表列出的替换元素。The .NET Framework defines the substitution elements listed in the following table.

替换Substitution 描述Description
$ number$ number 包括替换字符串中的由 number标识的捕获组所匹配的最后一个子字符串,其中 number 是一个十进制值。Includes the last substring matched by the capturing group that is identified by number, where number is a decimal value, in the replacement string. 有关详细信息,请参阅 替换已编号的组For more information, see Substituting a Numbered Group.
${ name }${ name } 包括替换字符串中由 (?<name> ) 指定的命名组所匹配的最后一个子字符串。Includes the last substring matched by the named group that is designated by (?<name> ) in the replacement string. 有关详细信息,请参阅 替换命名组For more information, see Substituting a Named Group.
$$ 包括替换字符串中的单个“$”文本。Includes a single "$" literal in the replacement string. 有关详细信息,请参阅 替换“$”符号For more information, see Substituting a "$" Symbol.
$& 包括替换字符串中整个匹配项的副本。Includes a copy of the entire match in the replacement string. 有关详细信息,请参阅 替换整个匹配项For more information, see Substituting the Entire Match.
$` 包括替换字符串中的匹配项前的输入字符串的所有文本。Includes all the text of the input string before the match in the replacement string. 有关详细信息,请参阅 替换匹配项前的文本For more information, see Substituting the Text before the Match.
$'$' 包括替换字符串中的匹配项后的输入字符串的所有文本。Includes all the text of the input string after the match in the replacement string. 有关详细信息,请参阅 替换匹配项后的文本For more information, see Substituting the Text after the Match.
$+ 包括在替换字符串中捕获的最后一个组。Includes the last group captured in the replacement string. 有关详细信息,请参阅 替换最后捕获的组For more information, see Substituting the Last Captured Group.
$_ 包括替换字符串中的整个输入字符串。Includes the entire input string in the replacement string. 有关详细信息,请参阅 替换整个输入字符串For more information, see Substituting the Entire Input String.

替换元素和替换模式Substitution Elements and Replacement Patterns

替换是替换模式中唯一可识别的特殊构造。Substitutions are the only special constructs recognized in a replacement pattern. 与任何字符匹配的其他正则表达式语言元素(包括字符转义和句点 (.))均不受支持。None of the other regular expression language elements, including character escapes and the period (.), which matches any character, are supported. 同样,替换语言元素只能在替换模式中识别,并且在正则表达式模式中永远无效。Similarly, substitution language elements are recognized only in replacement patterns and are never valid in regular expression patterns.

可以出现在正则表达式模式或替换中的唯一字符是 $ 字符,尽管它在每个上下文中具有不同的含义。The only character that can appear either in a regular expression pattern or in a substitution is the $ character, although it has a different meaning in each context. 在正则表达式模式中, $ 是与字符串的末尾匹配的定位点。In a regular expression pattern, $ is an anchor that matches the end of the string. 在替换模式中, $ 指示替换的开头。In a replacement pattern, $ indicates the beginning of a substitution.

备注

对于类似于正则表达式中替换模式的功能,使用反向引用。For functionality similar to a replacement pattern within a regular expression, use a backreference. 有关反向引用的更多信息,请参见 反向引用构造For more information about backreferences, see Backreference Constructs.

替换已编号的组Substituting a Numbered Group

$number 语言元素包括替换字符串中 number 捕获组所匹配的最后一个子字符串,其中 number 是捕获组的索引。The $number language element includes the last substring matched by the number capturing group in the replacement string, where number is the index of the capturing group. 例如,替换模式 $1 指示匹配的子字符串将由捕获的第一个组替换。For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. 有关为已编号的捕获组的详细信息,请参见 分组构造For more information about numbered capturing groups, see Grouping Constructs.

$ 后面的所有数字解释为属于 number 组。All digits that follow $ are interpreted as belonging to the number group. 如果这不是你想要的结果,可改为替换命名组。If this is not your intent, you can substitute a named group instead. 例如,可以使用替换字符串 ${1}1 而不是 $11 来将替换字符串定义为带数字“1”的首个捕获组的值。For example, you can use the replacement string ${1}1 instead of $11 to define the replacement string as the value of the first captured group along with the number "1". 有关详细信息,请参阅 替换命名组For more information, see Substituting a Named Group.

没有使用 (?<name>) 语法显式分配的名称的捕获组从左到右进行编号(从 1 开始)。Capturing groups that are not explicitly assigned names using the (?<name>) syntax are numbered from left to right starting at one. 命名组还从左到右进行编号,从比最后一个未命名组的索引大 1 的值开始。Named groups are also numbered from left to right, starting at one greater than the index of the last unnamed group. 例如,在正则表达式 (\w)(?<digit>\d)中, digit 命名组的索引为 2。For example, in the regular expression (\w)(?<digit>\d), the index of the digit named group is 2.

如果 number 未指定在正则表达式模式中定义的有效捕获组, $number 将被解释为用于替换每个匹配项的文本字符序列。If number does not specify a valid capturing group defined in the regular expression pattern, $number is interpreted as a literal character sequence that is used to replace each match.

下面的示例使用 $number 替换去除十进制值中的货币符号。The following example uses the $number substitution to strip the currency symbol from a decimal value. 它移除在货币值的开头或末尾找到的货币符号,并识别两个最常见的小数点分隔符(“.”和“,”)。It removes currency symbols found at the beginning or end of a monetary value, and recognizes the two most common decimal separators ("." and ",").

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}* 的定义如下表所示。The regular expression pattern \p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}* is defined as shown in the following table.

模式Pattern 描述Description
\p{Sc}* 与零个或多个货币符号字符匹配。Match zero or more currency symbol characters.
\s? 匹配零个或一个空白字符。Match zero or one white-space characters.
\d+ 匹配一个或多个十进制数字。Match one or more decimal digits.
[.,]? 与零个或一个句点或逗号匹配。Match zero or one period or comma.
\d* 匹配零个或多个十进制数字。Match zero or more decimal digits.
(\s?\d+[.,]?\d*) 匹配空白,后跟一个或多个十进制数,再后跟零个或一个句点或逗号,后跟零个或多个十进制数。Match a white space followed by one or more decimal digits, followed by zero or one period or comma, followed by zero or more decimal digits. 这是第一个捕获组。This is the first capturing group. 因为替换模式为 $1,所以调用 Regex.Replace 方法会将整个匹配的子字符串替换为此捕获组。Because the replacement pattern is $1, the call to the Regex.Replace method replaces the entire matched substring with this captured group.

替换命名组Substituting a Named Group

${name} 语言元素替换 name 捕获组匹配的最后一个子字符串,其中 name(?<name>) 语言元素所定义的捕获组名称。The ${name} language element substitutes the last substring matched by the name capturing group, where name is the name of a capturing group defined by the (?<name>) language element. 有关命名的捕获组的详细信息,请参见 分组构造For more information about named capturing groups, see Grouping Constructs.

如果 name 未指定正则表达式模式中定义的有效的命名捕获组但包含数字,则 ${name} 被解释为已编号的组。If name doesn't specify a valid named capturing group defined in the regular expression pattern but consists of digits, ${name} is interpreted as a numbered group.

如果 name 既未指定有效的命名捕获组也未指定正则表达式模式中定义的有效的已编号捕获组,则 ${name} 被解释为用于替换每个匹配的文本字符序列。If name specifies neither a valid named capturing group nor a valid numbered capturing group defined in the regular expression pattern, ${name} is interpreted as a literal character sequence that is used to replace each match.

下面的示例使用 ${name} 替换去除十进制值中的货币符号。The following example uses the ${name} substitution to strip the currency symbol from a decimal value. 它移除在货币值的开头或末尾找到的货币符号,并识别两个最常见的小数点分隔符(“.”和“,”)。It removes currency symbols found at the beginning or end of a monetary value, and recognizes the two most common decimal separators ("." and ",").

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}* 的定义如下表所示。The regular expression pattern \p{Sc}*(?<amount>\s?\d[.,]?\d*)\p{Sc}* is defined as shown in the following table.

模式Pattern 描述Description
\p{Sc}* 与零个或多个货币符号字符匹配。Match zero or more currency symbol characters.
\s? 匹配零个或一个空白字符。Match zero or one white-space characters.
\d+ 匹配一个或多个十进制数字。Match one or more decimal digits.
[.,]? 与零个或一个句点或逗号匹配。Match zero or one period or comma.
\d* 匹配零个或多个十进制数字。Match zero or more decimal digits.
(?<amount>\s?\d[.,]?\d*) 匹配空白,后跟一个或多个十进制数,再后跟零个或一个句点或逗号,后跟零个或多个十进制数。Match a white space, followed by one or more decimal digits, followed by zero or one period or comma, followed by zero or more decimal digits. 这是名为 amount的捕获组。This is the capturing group named amount. 因为替换模式为 ${amount},所以调用 Regex.Replace 方法会将整个匹配的子字符串替换为此捕获组。Because the replacement pattern is ${amount}, the call to the Regex.Replace method replaces the entire matched substring with this captured group.

替换“$”字符Substituting a "$" Character

$$ 替换将在替换的字符串中插入文本“$”字符。The $$ substitution inserts a literal "$" character in the replaced string.

下面的示例使用 NumberFormatInfo 对象确定当前区域性的货币符号及其在货币字符串中的位置。The following example uses the NumberFormatInfo object to determine the current culture's currency symbol and its placement in a currency string. 然后,它动态构建一个正则表达式模式和一个替换模式。It then builds both a regular expression pattern and a replacement pattern dynamically. 如果示例在当前区域性为 en-US 的计算机上运行,则它将生成正则表达式模式 \b(\d+)(\.(\d+))? 和替换模式 $$ $1$2If the example is run on a computer whose current culture is en-US, it generates the regular expression pattern \b(\d+)(\.(\d+))? and the replacement pattern $$ $1$2. 替换模式将匹配的文本替换为一个后跟第一个和第二个捕获组的货币符号和空格。The replacement pattern replaces the matched text with a currency symbol and a space followed by the first and second captured groups.

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("{0} --> {1}", 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+))? 的定义如下表所示。The regular expression pattern \b(\d+)(\.(\d+))? is defined as shown in the following table.

模式Pattern 描述Description
\b 从字边界开始进行匹配。Start the match at the beginning of a word boundary.
(\d+) 匹配一个或多个十进制数字。Match one or more decimal digits. 这是第一个捕获组。This is the first capturing group.
\. 与句点(小数点分隔符)匹配。Match a period (the decimal separator).
(\d+) 匹配一个或多个十进制数字。Match one or more decimal digits. 这是第三个捕获组。This is the third capturing group.
(\.(\d+))? 与零个或一个后跟一个或多个十进制数字的句点匹配。Match zero or one occurrence of a period followed by one or more decimal digits. 这是第二个捕获组。This is the second capturing group.

替换整个匹配项Substituting the Entire Match

$& 替换包括替换字符串中的整个匹配项。The $& substitution includes the entire match in the replacement string. 通常,它用于将子字符串添加至匹配字符串的开头或末尾。Often, it is used to add a substring to the beginning or end of the matched string. 例如, ($&) 替换模式向每个匹配项的开头和结尾添加括号。For example, the ($&) replacement pattern adds parentheses to the beginning and end of each match. 如果没有匹配项,则 $& 替换将不起作用。If there is no match, the $& substitution has no effect.

下面的示例使用 $& 替换在存储于字符串数组中的书名的开头和结尾添加引号。The following example uses the $& substitution to add quotation marks at the beginning and end of book titles stored in a string array.

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?)+$ 的定义如下表所示。The regular expression pattern ^(\w+\s?)+$ is defined as shown in the following table.

模式Pattern 描述Description
^ 从输入字符串的开头部分开始匹配。Start the match at the beginning of the input string.
(\w+\s?)+ 匹配一个或多个单词字符后跟零个或一个空白字符的模式一次或多次。Match the pattern of one or more word characters followed by zero or one white-space characters one or more times.
$ 匹配输入字符串的末尾部分。Match the end of the input string.

"$&" 替换模式将文本引号添加到每个匹配项的开头和结尾。The "$&" replacement pattern adds a literal quotation mark to the beginning and end of each match.

替换匹配项前的文本Substituting the Text Before the Match

$` 替换将匹配的字符串替换为匹配项前面的整个输入字符串。The $` substitution replaces the matched string with the entire input string before the match. 即,它将在删除匹配的文本时重复输入字符串,直至匹配。That is, it duplicates the input string up to the match while removing the matched text. 匹配文本后面的任何文本在结果字符串中保持不变。Any text that follows the matched text is unchanged in the result string. 如果输入字符串中有多个匹配项,则替换文本将派生自原始输入字符串,而不是派生自文本已由早期匹配项替换的字符串。If there are multiple matches in an input string, the replacement text is derived from the original input string, rather than from the string in which text has been replaced by earlier matches. (说明如示例所示。)如果没有匹配项,则 $` 替换将不起作用。(The example provides an illustration.) If there is no match, the $` substitution has no effect.

下面的示例使用正则表达式模式 \d+ 来匹配输入字符串中一个或多个十进制数字的序列。The following example uses the regular expression pattern \d+ to match a sequence of one or more decimal digits in the input string. 替换字符串 $` 将这些数字替换为该匹配项前的文本。The replacement string $` replaces these digits with the text that precedes the match.

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("   {0} at position {1}", match.Value, match.Index);

      Console.WriteLine("Input string:  {0}", 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" 包含五个匹配项。In this example, the input string "aa1bb2cc3dd4ee5" contains five matches. 下表说明了 $` 替换如何使正则表达式引擎替换输入字符串中的每个匹配项。The following table illustrates how the $` substitution causes the regular expression engine to replace each match in the input string. 插入文本在结果列中以粗体显示。Inserted text is shown in bold in the results column.

匹配Match 位置Position 匹配项前的字符串String before match 结果字符串Result string
11 22 aaaa aaaabb2cc3dd4ee5aaaabb2cc3dd4ee5
22 55 aa1bbaa1bb aaaabbaa1bbcc3dd4ee5aaaabbaa1bbcc3dd4ee5
33 88 aa1bb2ccaa1bb2cc aaaabbaa1bbccaa1bb2ccdd4ee5aaaabbaa1bbccaa1bb2ccdd4ee5
44 1111 aa1bb2cc3ddaa1bb2cc3dd aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddee5aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddee5
55 1414 aa1bb2cc3dd4eeaa1bb2cc3dd4ee aaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddeeaa1bb2cc3dd4eeaaaabbaa1bbccaa1bb2ccddaa1bb2cc3ddeeaa1bb2cc3dd4ee

替换匹配项后的文本Substituting the Text After the Match

$' 替换将匹配的字符串替换为匹配项后的整个输入字符串。The $' substitution replaces the matched string with the entire input string after the match. 即,它将在删除匹配的文本时重复匹配项后的输入字符串。That is, it duplicates the input string after the match while removing the matched text. 匹配文本前面的任何文本在结果字符串中保持不变。Any text that precedes the matched text is unchanged in the result string. 如果没有匹配项,则 $' 替换将不起作用。If there is no match, the $' substitution has no effect.

下面的示例使用正则表达式模式 \d+ 来匹配输入字符串中一个或多个十进制数字的序列。The following example uses the regular expression pattern \d+ to match a sequence of one or more decimal digits in the input string. 替换字符串 $' 将这些数字替换为匹配项后的文本。The replacement string $' replaces these digits with the text that follows the match.

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("   {0} at position {1}", match.Value, match.Index);
      Console.WriteLine("Input string:  {0}", 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" 包含五个匹配项。In this example, the input string "aa1bb2cc3dd4ee5" contains five matches. 下表说明了 $' 替换如何使正则表达式引擎替换输入字符串中的每个匹配项。The following table illustrates how the $' substitution causes the regular expression engine to replace each match in the input string. 插入文本在结果列中以粗体显示。Inserted text is shown in bold in the results column.

匹配Match 位置Position 匹配项后的字符串String after match 结果字符串Result string
11 22 bb2cc3dd4ee5bb2cc3dd4ee5 aabb2cc3dd4ee5bb2cc3dd4ee5aabb2cc3dd4ee5bb2cc3dd4ee5
22 55 cc3dd4ee5cc3dd4ee5 aabb2cc3dd4ee5bbcc3dd4ee5cc3dd4ee5aabb2cc3dd4ee5bbcc3dd4ee5cc3dd4ee5
33 88 dd4ee5dd4ee5 aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5dd4ee5aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5dd4ee5
44 1111 ee5ee5 aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee5aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee5
55 1414 String.Empty aabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5eeaabb2cc3dd4ee5bbcc3dd4ee5ccdd4ee5ddee5ee

替换最后捕获的组Substituting the Last Captured Group

$+ 替换将匹配的字符串替换为最后捕获的组。The $+ substitution replaces the matched string with the last captured group. 如果没有捕获组,或者最后的捕获组的值是 String.Empty,则 $+ 替换将不起作用。If there are no captured groups or if the value of the last captured group is String.Empty, the $+ substitution has no effect.

下面的示例标识字符串中的重复单词,并使用 $+ 替换将其替换为该单词的单一匹配项。The following example identifies duplicate words in a string and uses the $+ substitution to replace them with a single occurrence of the word. RegexOptions.IgnoreCase 选项用于确保大小写不同但其他内容都相同的单词被认为是重复的。The RegexOptions.IgnoreCase option is used to ensure that words that differ in case but that are otherwise identical are considered duplicates.

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 的定义如下表所示。The regular expression pattern \b(\w+)\s\1\b is defined as shown in the following table.

模式Pattern 描述Description
\b 在单词边界处开始匹配。Begin the match at a word boundary.
(\w+) 匹配一个或多个单词字符。Match one or more word characters. 这是第一个捕获组。This is the first capturing group.
\s 与空白字符匹配。Match a white-space character.
\1 与第一个捕获的组匹配。Match the first captured group.
\b 在单词边界处结束匹配。End the match at a word boundary.

替换整个输入字符串Substituting the Entire Input String

$_ 替换将匹配的字符串替换为整个输入字符。The $_ substitution replaces the matched string with the entire input string. 即,它将删除匹配的文本并将其替换为整个字符串(包括匹配的文本)。That is, it removes the matched text and replaces it with the entire string, including the matched text.

下面的示例匹配输入字符串中的一个或多个十进制数字。The following example matches one or more decimal digits in the input string. 它使用 $_ 替换来将其替换为整个输入字符串。It uses the $_ substitution to replace them with the entire input string.

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:          {0}", input);
      Console.WriteLine("String with substitution: {0}",
                        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" 包含两个匹配项。In this example, the input string "ABC123DEF456" contains two matches. 下表说明了 $_ 替换如何使正则表达式引擎替换输入字符串中的每个匹配项。The following table illustrates how the $_ substitution causes the regular expression engine to replace each match in the input string. 插入文本在结果列中以粗体显示。Inserted text is shown in bold in the results column.

匹配Match 位置Position 匹配Match 结果字符串Result string
11 33 123123 ABCABC123DEF456DEF456ABCABC123DEF456DEF456
22 55 456456 ABCABC123DEF456DEFABC123DEF456ABCABC123DEF456DEFABC123DEF456

请参阅See also