首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 正則表達式 TPerlRegEx 實戰 (4):Replace 替換操作詳解

     編輯:Delphi

TPerlRegEx 提供 ReplaceAll 整體替換與 Replace 單步替換兩種模式,搭配 MatchAgain 可實現精細控制。

基本替換:ReplaceAll

var 
  reg: TPerlRegEx; 
begin 
  reg := TPerlRegEx.Create(nil); 
  reg.RegEx := 'ab'; 
  reg.Replacement := '◆'; 
  reg.Subject := 'ababab'; 
  reg.ReplaceAll; 
  ShowMessage(reg.Subject); { 輸出: ◆◆◆ }
  
  FreeAndNil(reg); 
end;

手動迴圈替換:等價於 ReplaceAll

reg.Subject := 'ababab'; 

{ 下面四行等價於 reg.ReplaceAll }
while reg.MatchAgain do 
begin 
  reg.Replace; 
end; 

ShowMessage(reg.Subject); { 輸出: ◆◆◆ }

關鍵差異對照

方法回傳值行為適用場景
ReplaceAllBoolean (是否有替換發生)一次性全部替換簡單全域替換
Replacestring (Replacement 的值)單步替換當前匹配,需配合 MatchAgain需在替換中插入自訂邏輯

進階應用:條件式替換

while reg.MatchAgain do 
begin 
  { 根據匹配內容決定是否替換 }
  if SomeCondition(reg.MatchedExpression) then 
    reg.Replace 
  else 
    { 不替換,繼續下一個匹配 }
    ; 
end;

Replacement 字串中的特殊參考

  • $0 / \0:整個匹配內容
  • $1..$9 / \1..\9:第 1-9 子表達式捕獲內容
  • ${name}:具名捕獲組 (若支援)

掌握 Replace 迴圈模式,可實現 ReplaceAll 無法達成的複雜替換邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved