home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / delphi.swg / 0076_String Pattern matching.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1995-11-24  |  2.1 KB  |  64 lines

  1. {
  2. There are many times when you need to compare two strings, but want to use
  3. wild cards in the match - all last names that begin with 'St', etc.  The
  4. following is a piece of code I got from Sean Stanley in Tallahassee Florida
  5. in C.  I translated it into Delphi an am uploading it here for all to use.
  6. I have not tested it extensivly, but the original function has been tested
  7. quite thoughly.
  8.  
  9. I would love feedback on this routine - or peoples changes to it.  I want to
  10. forward them to Sean to get him to release more tidbits like this.
  11.  
  12. {
  13.   This function takes two strings and compares them.  The first string
  14.   can be anything, but should not contain pattern characters (* or ?).
  15.   The pattern string can have as many of these pattern characters as you want.
  16.   For example: MatchStrings('David Stidolph','*St*') would return True.
  17.  
  18.   Orignal code by Sean Stanley in C
  19.   Rewritten in Delphi by David Stidolph
  20. }
  21. function MatchStrings(source, pattern: String): Boolean;
  22. var
  23.   pSource: Array [0..255] of Char;
  24.   pPattern: Array [0..255] of Char;
  25.  
  26.   function MatchPattern(element, pattern: PChar): Boolean;
  27.  
  28.     function IsPatternWild(pattern: PChar): Boolean;
  29.     var
  30.       t: Integer;
  31.     begin
  32.       Result := StrScan(pattern,'*') <> nil;
  33.       if not Result then Result := StrScan(pattern,'?') <> nil;
  34.     end;
  35.  
  36.   begin
  37.     if 0 = StrComp(pattern,'*') then
  38.       Result := True
  39.     else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
  40.       Result := False
  41.     else if element^ = Chr(0) then
  42.       Result := True
  43.     else begin
  44.       case pattern^ of
  45.       '*': if MatchPattern(element,@pattern[1]) then
  46.              Result := True
  47.            else
  48.              Result := MatchPattern(@element[1],pattern);
  49.       '?': Result := MatchPattern(@element[1],@pattern[1]);
  50.       else
  51.         if element^ = pattern^ then
  52.           Result := MatchPattern(@element[1],@pattern[1])
  53.         else
  54.           Result := False;
  55.       end;
  56.     end;
  57.   end;
  58.  
  59. begin
  60.   StrPCopy(pSource,source);
  61.   StrPCopy(pPattern,pattern);
  62.   Result := MatchPattern(pSource,pPattern);
  63. end;
  64.