Determining if a string matches a pattern with wildcards ('?' and '*') (Views: 101)


Is there a LIKE function in Delphi that compares a string with a pattern?


Solve 1:

Sometimes we need to know if a string matches a pattern, which is a string with wildcards (for example '?' and '*'). Here we implement a function that returns True if the string matches the pattern and False if not.

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

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 in the article "Determining if a file name matches a specification" (keyword: MatchesSpec).

Solve 2:

There is a built in Delphi function called MatchesMask(). It takes * , ? and sets as parameters.

if MatchesMask('Hello World', '[H-K]?????[W-Y]*') then
if MatchesMask(FileName, '*.exe') then

Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

<< Back to main page