unit dregex;

interface

uses
  dstrings;

function MatchRegex(S, Regex: TAnsiBuf): Boolean;

implementation

function MatchRegex(S, Regex: TAnsiBuf): Boolean;
  function MatchStar(S, AfterStar: TAnsiBuf): Boolean;
  var
    I: LongInt;
  begin
    if (S.S = 0) and (AfterStar.S = 0) then
      Exit(True);
    for I := 0 to S.S do
      if MatchRegex(S.Skipped(I), AfterStar) then
        Exit(True);
    Exit(False);
  end;
var
  I: LongInt;
begin
  while S.S > 0 do begin
    if Regex.S = 0 then
      Exit(False);
    if Regex.First = '\' then begin
      Regex.Skip(1);
      if (Regex.S = 0) or (S.First <> Regex.First) then
        Exit(False);
    end else if Regex.First = '*' then begin
      Regex.Skip(1);
      Exit(MatchStar(S, Regex));
    end else if Regex.First = '.' then begin
      S.Skip(1);
      Regex.Skip(1);
    end else if Regex.First = '[' then begin
      Writeln(stderr, 'TODO: [a-zA-Z] expressions in MatchRegex');
      while Regex.First <> ']' do begin
        Regex.Skip(1 + Ord(Regex.First = '\'));
      end;
    end else if S.First = Regex.First then begin
      S.Skip(1);
      Regex.Skip(1);
    end else
      Exit(False);
  end;
  for I := 0 to Regex.S - 1 do
    if Regex[I] <> '*' then
      Exit(False);
  Exit(True);
end;

end.
