EscapeRegExChars 方法可自動為字串中的正則特殊字元加上反斜線轉義,避免手動轉義遺漏導致模式錯誤。
var
reg: TPerlRegEx;
begin
reg := TPerlRegEx.Create(nil);
reg.Subject := 'C++Builer';
{ 手寫 'C\+{2}' 容易出錯,用 EscapeRegExChars 自動處理 }
reg.RegEx := reg.EscapeRegExChars('C+') + '{2}'; { 相當於 'C\+{2}' }
reg.Replacement := '◆';
reg.ReplaceAll;
ShowMessage(reg.Subject); { 輸出: ◆Builer }
FreeAndNil(reg);
end;
^ $ ( ) [ ] { } . ? + * | \
{ 動態構建模式:搜尋使用者輸入的關鍵字 }
function BuildLiteralPattern(const Keyword: string): string;
var reg: TPerlRegEx;
begin
reg := TPerlRegEx.Create(nil);
try
Result := reg.EscapeRegExChars(Keyword);
finally
reg.Free;
end;
end;
善用 EscapeRegExChars 可大幅減少正則模式撰寫錯誤,特別是處理使用者輸入或外部資料時。