Title: Determining if a file name matches a specification
Question: 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.
function MatchesSpec(const FileName,
Specification: string): boolean;
var
SName, SExt, FName, FExt: string;
begin
FName := ExtractFileName(FileName);
SName := ExtractFileName(Specification);
FExt := ExtractFileExt(FName);
SExt := ExtractFileExt(SName);
SetLength(FName, Length(FName) - Length(FExt));
SetLength(SName, Length(SName) - Length(SExt));
if SName = '' then SName := '*';
if SExt = '' then SExt := '.*';
if FExt = '' then FExt := '.';
Result := Like(FName, SName) and Like(FExt, SExt);
end;
NOTE: The Like function has been featured in my article
"A simple Like function"
http://www.latiumsoftware.com/en/delphi/00018.html
Sample call
-----------
if MatchesSpec('Document1.doc', 'DOC*.DO?') then
ShowMessage('It worked!');