Help & Manual authoring tool
Sometimes we need to know if a filename matches a file specification (a name with wildcards: ? and *)...

Determining if a file name matches a specification

Copyright © 2000 Ernesto De Spirito

InstallAWARE - MSI without rocket science

MatchesSpec

Sometimes we need to know if a file name matches a file specification (a name with wildcards: ? and *). For this purpose you can use the MatchesMask function that is declared in the Masks unit, but here as a teaching example and because we believe it might be useful in certain cases (for example when you don't want sets), we implement a replacement function that returns True if the given file name matches a specification and False if not. Here is the source code:

uses SysUtils;

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;

Sample call

if MatchesSpec('Document1.doc', 'DOC*.DO?') then
  ShowMessage('It worked!');
JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.