Mega Code Archive

 
Categories / Delphi / String
 

String Pattern Matching. updt []

Title: String Pattern Matching. updt '[]' Question: Use it when you want to compare strings using '*' or '?' operator. Answer: The MatchPattern function take 2 strings and compare them using simple pattern matching. Only '*' and '?' are implemented, range syntaxe '[]' are implemented. Exemple : MatchPattern('autoexec.bat', '*.bat') = true, etc... MatchPattern('johnny', 'j[aeiou]hnny') = true MatchPattern('Yooha!', 'Y[a-z]oh[0-9]!') = false Notes : 14/11/00 the '15 1*5' bug is corrected. Thank to Paramjeet. A more complete version is available at http://www.delphi3000.com/article.asp?ID=1561 function MatchPattern(s : PCHAR; pattern : PCHAR) : boolean; {* simple pattern matching * metachar are :'*', '?', '[x-y]' (range), '[wxyz]' * translated from MatchPattern() of common.c in MSDN Samples\VC98\sdk\sdktools\tlist *} var c : char; p : char; l : char; begin while (true) do begin p := Pattern^; inc(Pattern); case p of #0 : begin // End of pattern result := s^ = #0; // if end of string TRUE exit; end; '*': begin while(bool(s^)) do begin // Match zero or more char if(MatchPattern(s, pattern)) then begin result := true; exit; inc(s); // Thanks to Paramjeet end; end; result := MatchPattern(s, pattern); exit; end; '?': begin if (s^ = #0) then begin // match any one char result := false; // not end of string exit; end; inc(s); end; '[' : begin c := s^; // c = *s++ inc(s); // match char set [0123] or [0-3] if (c = #0) then begin result := false; exit; end; l := #0; p := pattern^; inc(pattern); while (bool(p)) do begin if (p = ']') then begin // if end of char set, then no match found result := false; exit; end; if (p = '-') then begin // check a ronge of char ? p := pattern^; if (p = #0) or (p = ']') then begin // Get high limit of range result := false; exit; end; if (c = l) and (c begin break; // if in range, move on (redo while) end; end; l := p; if (c = p) then break; // if char matches this element, move on (redo while) p := pattern^; inc(pattern); end; while (bool(p) and (p ']')) do begin // got a match in char set p := pattern^; inc(pattern); // skip to end of set end; end; else begin c := s^; inc(s); if (c p) then begin // check for exact char result := false; exit; end; end; end; end; end; Note : this is 50% faster than the Eva Hummer function, using D3. http://www.delphi3000.com/article.asp?id=639