高階替換
一些程式語言有自己的正規表示式特性,例如,$+術語(在 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