Determining if a file name matches a specification (Views: 100)


How can I know if a file name matches a specification with wildcards?


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;
  SName, SExt, FName, FExt: string;
  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);

NOTE: The Like function has been featured in my article  
"Determining if a string matches a pattern with wildcards ('?' and '*')"

Sample call

if MatchesSpec('Document1.doc', 'DOC*.DO?') then
  ShowMessage('It worked!');

Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

<< Back to main page