A function that uses wildcards (? and *) for string comparisons

A simple Like function

Copyright © 2000 Ernesto De Spirito

Pascal Newsletter. Free ezine for Delphi (and Kylix) programmers with articles, news, reviews, tips, trinks, and links to new Delphi content on the web!

Like

Sometimes we need to know if a string matches a pattern, which is a string with wildcards (for example ? and *). For this purpose you can use the MatchesMask function that is declared in the Masks unit, but here as a teaching example and because we believe it might be useful in certain cases (for example when you don't want sets), we implement a replacement function that returns True if the string matches the pattern and False if not. Here is the source code:

uses SysUtils;

function Like(AString, Pattern: string): boolean;
var
  i, n, n1, n2: integer;
  p1, p2: pchar;
label
  match, nomatch;
begin
  AString := UpperCase(AString);
  Pattern := UpperCase(Pattern);
  n1 := Length(AString);
  n2 := Length(Pattern);
  if n1 < n2 then n := n1 else n := n2;
  p1 := pchar(AString);
  p2 := pchar(Pattern);
  for i := 1 to n do begin
    if p2^ = '*' then goto match;
    if (p2^ <> '?') and (p2^ <> p1^) then goto nomatch;
    inc(p1); inc(p2);
  end;
  if n1 > n2 then begin
nomatch:
    Result := False;
    exit;
  end else if n1 < n2 then begin
    for i := n1 + 1 to n2 do begin
      if not (p2^ in ['*','?']) then goto nomatch;
      inc(p2);
    end;
  end;
match:
  Result := True;
end;

Sample call

if Like('Walter', 'WA?T*') then
  ShowMessage('It worked!');

If you want to see another example, we use this function to determine if a file name matches a specification.

JfControls Library - for Delphi and C++ Builder