본문 바로가기

Delphi/C++Builder

[Delphi] Wild Card 문자비교

문자열에서 Wild Card('?': single character, '*': multi character)를 포함하여 비교한다.
function MatchString(ASource, APattern: String): Boolean;
  function _MatchPattern(element, pattern: PChar): Boolean;
  begin
    if 0 = StrComp(pattern, '*') then
      Result := True
    else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
      Result := False
    else if element^ = Chr(0) then
      Result := True
    else
    begin
      case pattern^ of
      '*': if _MatchPattern(element, @pattern[1]) then
             Result := True
           else
             Result := _MatchPattern(@element[1],pattern);
      '?': Result := _MatchPattern(@element[1],@pattern[1]);
      else
        if element^ = pattern^ then
          Result := _MatchPattern(@element[1],@pattern[1])
        else
          Result := False;
      end;
    end;
  end;
var
  pSource, pPattern: PChar;
begin
  pSource   := StrAlloc(Length(ASource)+1);
  pPattern  := StrAlloc(Length(APattern)+1);
  try
    StrPCopy(pSource,   ASource);
    StrPCopy(pPattern,  APattern);

    Result := _MatchPattern(pSource, pPattern);
  finally
    StrDispose(pSource);
    StrDispose(pPattern);
  end;
end;
출처 : 인터넷 어딘가...:-)
// sample
var 
  source: string;
  target: string;
begin
  source := 'abcdefg';
  target := 'ab*e?g';  // correct('cd' = '*', 'f' = '?')

  if MatchString(source, target) then  
    ShowMessage('Correct match')
  else 
    ShowMessage('Incorrect match')
  ;
end;