TPerlRegEx 提供多種查找模式,從簡單存在性檢查到完整遍歷所有匹配,涵蓋所有常見需求。
var reg: TPerlRegEx;
begin
reg := TPerlRegEx.Create(nil);
reg.Subject := 'CodeGear Delphi 2007 for Win32';
reg.RegEx := '\d'; { 匹配任意數字 }
if reg.Match then
ShowMessage('找到了')
else
ShowMessage('沒找到');
FreeAndNil(reg);
end;
reg.Match; { 執行查找 }
if reg.FoundMatch then { 布林屬性告知結果 }
ShowMessage('找到了')
else
ShowMessage('沒找到');
if reg.Match then
ShowMessage(reg.MatchedExpression) { 輸出: 2 }
else
ShowMessage('沒找到');
var num: Integer;
begin
num := 0;
while reg.MatchAgain do { MatchAgain 尋找下一個 }
begin
ShowMessage(reg.MatchedExpression); { 依序輸出: 2, 0, 0, 7, 3, 2 }
Inc(num);
end;
ShowMessage(IntToStr(num)); { 總計: 6 }
end;
num := 0;
if reg.Match then
begin
repeat
ShowMessage(reg.MatchedExpression);
Inc(num);
until (not reg.MatchAgain);
end;
ShowMessage(IntToStr(num)); { 6 }
while reg.MatchAgain do
begin
ShowMessage(reg.MatchedExpression); { Delphi }
ShowMessage(IntToStr(reg.MatchedExpressionOffset)); { 位置: 10 (1-based) }
ShowMessage(IntToStr(reg.MatchedExpressionLength)); { 長度: 6 }
end;
| 成員 | 型別 | 說明 |
|---|---|---|
Match | function: Boolean | 從頭開始搜尋 (重置位置) |
MatchAgain | function: Boolean | 從上次匹配結束處繼續搜尋 |
FoundMatch | property: Boolean | 最近一次 Match/MatchAgain 是否成功 |
MatchedExpression | property: string | 最近匹配的完整字串 |
MatchedExpressionOffset | property: Integer | 匹配起始位置 (1-based) |
MatchedExpressionLength | property: Integer | 匹配字串長度 |
Match + FoundMatchMatch + MatchedExpressionwhile MatchAgain do 迴圈Offset/Length 屬性掌握這六種查找模式,即可應對 95% 的正則查找需求。