String pattern matching

There are many times when you need to compare two strings, but want to use wild cards in the match - all last names that begin with 'St', etc.


The following is a piece of code I got from Sean Stanley in Tallahassee Florida in C. I translated it into Delphi an am uploading it here for all to use. I have not tested it extensivly, but the original function has been tested quite thoughly.

I would love feedback on this routine - or peoples changes to it. I want to forward them to Sean to get him to release more tidbits like this.


  This function takes two strings and compares them. The first string

  can be anything, but should not contain pattern characters (* or ?).

  The pattern string can have as many of these pattern characters as you want.

  For example: MatchStrings('David Stidolph','*St*') would return True.

  Orignal code by Sean Stanley in C

  Rewritten in Delphi by David Stidolph


function MatchStrings(source, pattern: String): Boolean;


  pSource: Array [0..255] of Char;

  pPattern: Array [0..255] of Char;

  function MatchPattern(element, pattern: PChar): Boolean;

    function IsPatternWild(pattern: PChar): Boolean;


      t: Integer;


      Result := StrScan(pattern,'*') <> nil;

      if not Result then Result := StrScan(pattern,'?') <> nil;



    if 0 = StrComp(pattern,'*') then

      Result := True

    else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then

      Result := False

    else if element^ = Chr(0) then

      Result := True

    else begin

      case pattern^ of

      '*': if MatchPattern(element,@pattern[1]) then

             Result := True


             Result := MatchPattern(@element[1],pattern);

      '?': Result := MatchPattern(@element[1],@pattern[1]);


        if element^ = pattern^ then

          Result := MatchPattern(@element[1],@pattern[1])


          Result := False;







  Result := MatchPattern(pSource,pPattern);



Share this article!

Follow us!

Find more helpful articles: