Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string from a text file using 2 delimiters

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.

like image 565
Gab Avatar asked Feb 09 '11 21:02

Gab


4 Answers

Get em all

function ExtractText(const Str: string; const Delim1, Delim2: string): TStringList;
var
  c,pos1, pos2: integer;
begin
  result:=TStringList.Create;
  c:=1;
  pos1:=1;

  while pos1>0 do
  begin
    pos1 := PosEx(Delim1, Str,c);
    if pos1 > 0 then begin
      pos2 := PosEx(Delim2, Str, pos1+1);
    if pos2 > 0 then
      result.Add(Copy(Str, pos1 + length(delim1), pos2 - (length(delim1) + pos1)));
      c:=pos1+1;
     end;

  end;
end;
like image 166
poetra Avatar answered Oct 19 '22 14:10

poetra


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;
like image 26
Arnaud Bouchez Avatar answered Nov 15 '22 12:11

Arnaud Bouchez


You can do it with Pos and Copy:

function ExtractText(const Str: string; const Delim1, Delim2: char): string;
var
  pos1, pos2: integer;
begin
  result := '';
  pos1 := Pos(Delim1, Str);
  pos2 := Pos(Delim2, Str);
  if (pos1 > 0) and (pos2 > pos1) then
    result := Copy(Str, pos1 + 1, pos2 - pos1 - 1);
end;
like image 12
Andreas Rejbrand Avatar answered Nov 15 '22 13:11

Andreas Rejbrand


I'd do it something like this:

function ExtractDelimitedString(const s: string): string;
var
  p1, p2: Integer;
begin
  p1 := Pos('$', s);
  p2 := Pos('/', s);
  if (p1<>0) and (p2<>0) and (p2>p1) then begin
    Result := Copy(s, p1+1, p2-p1-1);
  end else begin
    Result := '';//delimiters not found, or in the wrong order; raise error perhaps
  end;
end;
like image 11
David Heffernan Avatar answered Nov 15 '22 14:11

David Heffernan