Delphi – Extract string from a text file using 2 delimiters

delphi, extract, string

I'm trying to extract a string from a text file using 2 delimiters. One to start and one to stop.

Example:

Hi my name is$John and I'm happy/today

What I need to do is to call a function that would return the string between $ and /. I've been looking everywhere but I can't seem to find something useful and I'm new to programming.

Best Solution

The above functions won't work if the 2nd text is also appearing before the 1st pattern...

You should use PosEx() instead of Pos():

You can do it with Pos and Copy:

function ExtractText(const Str: string; const Delim1, Delim2: string): string;var  pos1, pos2: integer;begin  result := '';  pos1 := Pos(Delim1, Str);  if pos1 > 0 then begin    pos2 := PosEx(Delim2, Str, pos1+1);    if pos2 > 0 then      result := Copy(Str, pos1 + 1, pos2 - pos1 - 1);  end;end;