HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Function to find text between two tags

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
textfunctiontagstwobetweenfind

Problem

I've just finished this function and wanted to know if anyone know another way to do the same:

function findtext(archivo,Delimit1, Delimit2 :String) :String;
var
  Buffer      :AnsiString;
  ResLength   :Integer;
  i           :Integer;
  PosDelimit  :Integer;
begin
  Buffer := read_file_z(archivo);
  if Pos(Delimit1, Buffer) > Pos(Delimit2, Buffer) then
    PosDelimit := Length(Buffer)-(Pos(Delimit1, Buffer)+Length(Delimit1))
  else PosDelimit := Length(Buffer)-(Pos(Delimit2, Buffer)+Length(Delimit2));
  Buffer := Copy(Buffer, (Length(Buffer)-PosDelimit), Length(Buffer));
  ResLength := Pos(Delimit2, Buffer)-(Pos(Delimit1, Buffer)+Length(Delimit1));
  for i := 0 to (Reslength-1) do
    Result := Result+Buffer[Pos(Delimit1, Buffer)+(Length(Delimit1)+i)];
end;


The auxiliary function read_file_z is this:

function read_file_z(const FileName: String): AnsiString;
var
  F: File;
  DefaultFileMode: Byte;
begin
  DefaultFileMode := FileMode;
  try
    FileMode := 0;
    AssignFile(F, FileName);
    {$I-}
    Reset(F, 1);
    {$I+}
    if IoResult=0 then
      try
        SetLength(Result,FileSize(F));
        if Length(Result)>0 then begin
          {$I-}
          BlockRead(F,Result[1],LENGTH(Result));
          {$I+}
          if IoResult<>0 then Result:='';
        end;
      finally
        CloseFile(F);
      end;
  finally
    FileMode := DefaultFileMode;
  end;
end;


The function finds text between two tags. An example would [hi]hi world[hi] and the function will respond "hi world".

Example:

findtext('test.exe','[hi]','[hi]');


The way seek to do the function is the "uses" default.

What alternatives do I have to make the function "findtext"?

Solution

You code is extremly hard to read. But I belive this is what you are looking for:

function FindText(FileName: TFilename; const Delimit1, Delimit2: string): string;
var
  Buffer: TStringList;
  PD1, PD2: Integer;
begin
  Buffer := TStringList.Create;
  try
    Buffer.LoadFromFile(FileName);

    PD1 := Pos(Delimit1, Buffer.Text) + Length(Delimit1);
    PD2 := Pos(Delimit2, Buffer.Text);

    Result := Copy(Buffer.Text, PD1, PD2 - PD1);
  finally
    FreeAndNil(Buffer);
  end;
end;

Code Snippets

function FindText(FileName: TFilename; const Delimit1, Delimit2: string): string;
var
  Buffer: TStringList;
  PD1, PD2: Integer;
begin
  Buffer := TStringList.Create;
  try
    Buffer.LoadFromFile(FileName);

    PD1 := Pos(Delimit1, Buffer.Text) + Length(Delimit1);
    PD2 := Pos(Delimit2, Buffer.Text);

    Result := Copy(Buffer.Text, PD1, PD2 - PD1);
  finally
    FreeAndNil(Buffer);
  end;
end;

Context

StackExchange Code Review Q#82368, answer score: 4

Revisions (0)

No revisions yet.