Author: Tomas Rutkauskas
How to implement string pattern matching with wildcards
Answer:
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.
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.}
1
2 function MatchStrings(source, pattern: string): Boolean;
3 var
4 pSource: array[0..255] of Char;
5 pPattern: array[0..255] of Char;
6
7 function MatchPattern(element, pattern: PChar): Boolean;
8
9 function IsPatternWild(pattern: PChar): Boolean;
10 var
11 t: Integer;
12 begin
13 Result := StrScan(pattern, ' * ') <> nil;
14 if not Result then
15 Result := StrScan(pattern, ' ? ') <> nil;
16 end;
17
18 begin
19 if 0 = StrComp(pattern, ' * ') then
20 Result := True
21 else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
22 Result := False
23 else if element^ = Chr(0) then
24 Result := True
25 else
26 begin
27 case pattern^ of
28 ' * ':
29 if MatchPattern(element, @pattern[1]) then
30 Result := True
31 else
32 Result := MatchPattern(@element[1], pattern);
33 ' ? ':
34 Result := MatchPattern(@element[1], @pattern[1]);
35 else
36 if element^ = pattern^ then
37 Result := MatchPattern(@element[1], @pattern[1])
38 else
39 Result := False;
40 end;
41 end;
42 end;
43
44 begin
45 StrPCopy(pSource, source);
46 StrPCopy(pPattern, pattern);
47 Result := MatchPattern(pSource, pPattern);
48 end;
|