高级替换

一些编程语言有自己的正则表达式特性,例如,$+术语(在 C#,Perl,VB 等中)将匹配的文本替换为捕获的最后一个组。

例:

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.

Microsoft 官方开发者网络示例 [1]

其他罕见的替代术语是$` $'

$` =替换匹配字符串的文本匹配
$' = 将匹配字符串替换为匹配字符串的文本

由于这个事实,这些替换字符串应该像这样工作:

Regex: /part2/
Input: "part1part2part3"
Replacement: "$`"
Output: "part1part1part3" //Note that part2 was replaced with part1, due &` termRegex: /part2/
Input: "part1part2part3"
Replacement: "$'"
Output: "part1part3part3" //Note that part2 was replaced with part3, due &' term

以下是在一段 javascript 上进行这些替换的示例:

var rgx = /middle/;
var text = "Your story must have a beginning, middle, and end"
console.log(text.replace(rgx, "$`")); 
//Logs: "Your story must have a beginning, Your story must have a beginning, , and end"
console.log(text.replace(rgx, "$'"))
//Logs: "Your story must have a beginning, , and end, and end"

还有术语 $_,它可以检索整个匹配的文本:

Regex: /part2/
Input: "part1part2part3"
Replacement: "$_"
Output: "part1part1part2part3part3" //Note that part2 was replaced with part1part2part3,
                                                                         // due $_ term

将其转换为 VB 将为我们提供:

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

Microsoft 官方开发者网络示例 [2]

并且最后但并非最不重要的替换术语是 $$,其转换为正则表达式将与\$(文字 $ 的转义版本 )相同。

如果你想匹配一个像这样的字符串:例如 USD: $3.99,并想要存储 3.99,但只用一个正则表达式替换为 $3.99,你可以使用:

Regex: /USD:\s+\$([\d.]+)/
Input: "USD: $3.99"
Replacement: "$$$1"
To Store: "$1"
Output: "$3.99"
Stored: "3.99"

如果你想使用 Javascript 进行测试,可以使用以下代码:

var rgx = /USD:\s+\$([\d.]+)/;
var text = "USD: $3.99";
var stored = parseFloat(rgx.exec(text)[1]);
console.log(stored); //Logs 3.99
console.log(text.replace(rgx, "$$$1")); //Logs $3.99

参考

[1]: 替换最后捕获的组
[2]: 替换整个输入字符串