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

Delphi 正則表達式 TPerlRegEx 實戰 (1):Match/MatchAgain 查找操作全模式

     編輯:Delphi

TPerlRegEx 提供多種查找模式,從簡單存在性檢查到完整遍歷所有匹配,涵蓋所有常見需求。

模式 1:單次匹配檢查存在性

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;

模式 2:Match + FoundMatch 屬性

reg.Match; { 執行查找 }
if reg.FoundMatch then { 布林屬性告知結果 }
  ShowMessage('找到了') 
else 
  ShowMessage('沒找到');

模式 3:取得第一個匹配內容

if reg.Match then 
  ShowMessage(reg.MatchedExpression) { 輸出: 2 }
else 
  ShowMessage('沒找到');

模式 4:遍歷所有匹配 (While MatchAgain)

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;

模式 5:Repeat-Until 等價寫法

num := 0; 
if reg.Match then 
begin 
  repeat 
    ShowMessage(reg.MatchedExpression); 
    Inc(num); 
  until (not reg.MatchAgain); 
end; 
ShowMessage(IntToStr(num)); { 6 }

模式 6:取得匹配位置與長度

while reg.MatchAgain do 
begin 
  ShowMessage(reg.MatchedExpression); { Delphi }
  ShowMessage(IntToStr(reg.MatchedExpressionOffset)); { 位置: 10 (1-based) }
  ShowMessage(IntToStr(reg.MatchedExpressionLength)); { 長度: 6 }
end;

核心方法/屬性速查

成員型別說明
Matchfunction: Boolean從頭開始搜尋 (重置位置)
MatchAgainfunction: Boolean從上次匹配結束處繼續搜尋
FoundMatchproperty: Boolean最近一次 Match/MatchAgain 是否成功
MatchedExpressionproperty: string最近匹配的完整字串
MatchedExpressionOffsetproperty: Integer匹配起始位置 (1-based)
MatchedExpressionLengthproperty: Integer匹配字串長度

最佳實踐建議

  • 單次檢查用 Match + FoundMatch
  • 需匹配內容用 Match + MatchedExpression
  • 遍歷所有用 while MatchAgain do 迴圈
  • 需位置資訊直接讀取 Offset/Length 屬性

掌握這六種查找模式,即可應對 95% 的正則查找需求。

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