Author: Ernesto De Spirito
How can I know if a file name matches a specification with wildcards?
Answer:
Sometimes we need to know if a file name matches a file specification (a name with
wildcards: '?' and '*'). Here we implement a function that returns True if the
given file name matches a specification and False if not.
1 2 function MatchesSpec(const FileName,
3 Specification: string): boolean;
4 var5 SName, SExt, FName, FExt: string;
6 begin7 FName := ExtractFileName(FileName);
8 SName := ExtractFileName(Specification);
9 FExt := ExtractFileExt(FName);
10 SExt := ExtractFileExt(SName);
11 SetLength(FName, Length(FName) - Length(FExt));
12 SetLength(SName, Length(SName) - Length(SExt));
13 if SName = '' then14 SName := '*';
15 if SExt = '' then16 SExt := '.*';
17 if FExt = '' then18 FExt := '.';
19 Result := Like(FName, SName) and Like(FExt, SExt);
20 end;
NOTE: The Like function has been featured in my article
"Determining if a string matches a pattern with wildcards ('?' and
'*')dkb://542874283"
Sample call
21 if MatchesSpec('Document1.doc', 'DOC*.DO?') then22 ShowMessage('It worked!');
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.php