Jump to content
slacky

PregMatchAll(Ex)

Recommended Posts

Yesterday I created a couple of functions, you will most likely find am in a future release of MSSL (I've talked to Janilabo about am).

 

These functions matches a regular expression defined by Pattern in a string defined by Subject. They are partially formed after: PHP => preg_match_all

 

PregMatchAll returns all the found results in a TStrArray (Array of String).

 

PregMatchAllEx on the other hand acts like PregMatchEx, it takes a third parameter Matches, where the result-array will be outputted; in an Array of TRegexMatchArray (I have called it T2DRegexMatchArray). The Function-Result is ether True, or False (depending on if it found any matches).

 

PregMatchAllEx(pattern, subject: string; var Matches:T2DRegexMatchArray): Boolean;

type
 T2DRegexMatchArray = Array of TRegexMatchArray; 

function PregMatchAllEx(pattern, subject: string; var Matches:T2DRegexMatchArray): Boolean;
var
 MarchArr: TRegexMatchArray;  
 CurpossE, size: Integer;
begin
 Result := False;
 while PregMatchEx(pattern, subject, MarchArr) do 
 begin                                                 
   CurpossE := (Length(MarchArr[0].MatchedText) + MarchArr[0].OffSet);
   subject := Right(subject, (Length(subject) - CurpossE));
   size := Length(Matches)
   SetLength(Matches, size + 1);
   Matches[size] := MarchArr;
 end;
 if Length(Matches)>0 then
   Result := True    
end;

 

PregMatchAll(pattern, subject: string): TStrArray;

function PregMatchAll(pattern, subject: string): TStrArray;
var
 matches: TRegexMatchArray;  
 CurpossE, size: Integer;
begin
 while PregMatchEx(pattern, subject, matches) do 
 begin                                                 
   CurpossE := (Length(matches[0].MatchedText) + Matches[0].OffSet);
   subject := Right(subject, (Length(subject) - CurpossE));   
   size := Length(Matches)
   SetLength(Result, size + 1);
   Result[size] := matches[0].MatchedText;
 end;    
end;

 

If you have used PregMatch, or PregMatchEx, the usage should be self-explanatory. The only difference is that these functions finds ALL the matches.

 

Thanks to Janilabo for cleaning PregMatchAll up a little (made it fairly easier to read).

Edited by slacky
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
  • Create New...