Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string between two strings

How can i extract randomstring between A & B. For example:

A randomstring B

like image 960
Nuno Jemaio Avatar asked Sep 17 '25 22:09

Nuno Jemaio


1 Answers

Assuming that "randomstring" doesn't contain the enclosing strings "A" or "B", you can use two calls to pos to extract the string:

function ExtractBetween(const Value, A, B: string): string;
var
  aPos, bPos: Integer;
begin
  result := '';
  aPos := Pos(A, Value);
  if aPos > 0 then begin
    aPos := aPos + Length(A);
    bPos := PosEx(B, Value, aPos);
    if bPos > 0 then begin
      result := Copy(Value, aPos, bPos - aPos);
    end;
  end;
end;

The function will return an empty string when either A or B are not found.

like image 179
Uwe Raabe Avatar answered Sep 20 '25 12:09

Uwe Raabe