How to extract a substring between two tags [start] [end] in a string with Pascal

1 Answer

0 votes
program ExtractBetweenTags;

{$mode objfpc}{$H+}

(*
 * Returns the substring between two tags.
 * Parameters:
 *   S       - input string
 *   StartTag, EndTag - tag delimiters
 *
 * Returns:
 *   Extracted substring, or empty string if tags not found.
 *)
function ExtractBetween(const S, StartTag, EndTag: string): string;
var
  p1, p2, startPos: Integer;
begin
  Result := '';

  p1 := Pos(StartTag, S);
  if p1 = 0 then Exit;

  startPos := p1 + Length(StartTag);

  p2 := Pos(EndTag, Copy(S, startPos, MaxInt));
  if p2 = 0 then Exit;

  Result := Copy(S, startPos, p2 - 1);
end;

procedure Extract;
var
  Text, Extracted: string;
begin
  Text := 'What do you [start]think about this[end] idea?';

  Extracted := ExtractBetween(Text, '[start]', '[end]');

  WriteLn('Extracted: ', Extracted);
end;

begin
  Extract;
end.



(*
run:

Extracted: think about this

*)

 



answered 4 hours ago by avibootz
...