Author: Ernesto De Spirito
Is there a LIKE function in Delphi that compares a string with a pattern?
Answer:
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.
1 function Like(AString, Pattern: string): boolean;
2 var3 i, n, n1, n2: integer;
4 p1, p2: pchar;
5 label6 match, nomatch;
7 begin8 AString := UpperCase(AString);
9 Pattern := UpperCase(Pattern);
10 n1 := Length(AString);
11 n2 := Length(Pattern);
12 if n1 < n2 then13 n := n1
14 else15 n := n2;
16 p1 := pchar(AString);
17 p2 := pchar(Pattern);
18 for i := 1 to n do19 begin20 if p2^ = '*' then21 goto match;
22 if (p2^ <> '?') and (p2^ <> p1^) then23 goto nomatch;
24 inc(p1);
25 inc(p2);
26 end;
27 if n1 > n2 then28 begin29 nomatch:
30 Result := False;
31 exit;
32 end33 elseif n1 < n2 then34 begin35 for i := n1 + 1 to n2 do36 begin37 ifnot (p2^ in ['*', '?']) then38 goto nomatch;
39 inc(p2);
40 end;
41 end;
42 match:
43 Result := True;
44 end;
Sample call
45 if Like('Walter', 'WA?T*') then46 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.
47 {...}48 if MatchesMask('Hello World', '[H-K]?????[W-Y]*') then49 50 {...}51 if MatchesMask(FileName, '*.exe') then52 53 {...}
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.php