Compare string with pattern

Posted in Algorithms

If you want to check your string with pattern, which has '?' symbol for changing any symbol, then you may use ComparePattern procedure. First parameter - is a mask, second - is your string and Check variable is result. Result is True, if your string matches with pattern.

procedure ComparePattern(St1, St2: string; var Check: Boolean);
var
  Hlp1, Hlp2: string;
  Pos1: Integer;
begin
  Check:=True;
  while Length(St1)>0 do
  begin
    Pos1:=Pos('?', St1);

    if (Pos1=0) then
    begin
      if CompareStr(St1, St2)<>0 then Check:=False;
      Delete(St1, 1, Length(St1));
      Delete(St2, 1, Length(St2));
    end;

    if (Pos1>0) then
    begin
      Hlp1:=Copy(St1,1,Pos1-1);
      Hlp2:=Copy(St2,1,Pos1-1);
      if CompareStr(Hlp1, Hlp2)<>0 then Check:=False;
      Delete(St1,1,Pos1);
      if Pos1>Length(St2) then Check:=False;
      Delete(St2,1,Pos1);
    end;

    if Check=False then Break;

  end;
  if CompareStr(St1, St2)<>0 then Check:=False;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Check: Boolean;
begin
  ComparePattern(Edit1.text, Edit2.Text, Check);
  if Check=True then Caption:='OK'
  else Caption:='Not OK';
end;