TPerlRegEx 提供 ReplaceAll 整體替換與 Replace 單步替換兩種模式,搭配 MatchAgain 可實現精細控制。
var
reg: TPerlRegEx;
begin
reg := TPerlRegEx.Create(nil);
reg.RegEx := 'ab';
reg.Replacement := '◆';
reg.Subject := 'ababab';
reg.ReplaceAll;
ShowMessage(reg.Subject); { 輸出: ◆◆◆ }
FreeAndNil(reg);
end;
reg.Subject := 'ababab';
{ 下面四行等價於 reg.ReplaceAll }
while reg.MatchAgain do
begin
reg.Replace;
end;
ShowMessage(reg.Subject); { 輸出: ◆◆◆ }
| 方法 | 回傳值 | 行為 | 適用場景 |
|---|---|---|---|
ReplaceAll | Boolean (是否有替換發生) | 一次性全部替換 | 簡單全域替換 |
Replace | string (Replacement 的值) | 單步替換當前匹配,需配合 MatchAgain | 需在替換中插入自訂邏輯 |
while reg.MatchAgain do
begin
{ 根據匹配內容決定是否替換 }
if SomeCondition(reg.MatchedExpression) then
reg.Replace
else
{ 不替換,繼續下一個匹配 }
;
end;
$0 / \0:整個匹配內容$1..$9 / \1..\9:第 1-9 子表達式捕獲內容${name}:具名捕獲組 (若支援)掌握 Replace 迴圈模式,可實現 ReplaceAll 無法達成的複雜替換邏輯。