使用2个分隔符从文本文件中提取字符串

Gab*_*Gab 9 delphi string extract

我正在尝试使用2个分隔符从文本文件中提取字符串.一个开始,一个停止.

例:

Hi my name is$John and I'm happy/today
Run Code Online (Sandbox Code Playgroud)

我需要做的是调用,将返回的字符串的函数$/.我一直在寻找各处,但我似乎找不到有用的东西,我是编程的新手.

And*_*and 12

你可以用PosCopy:

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;
Run Code Online (Sandbox Code Playgroud)

  • 使用[`PosEx`](http://docwiki.embarcadero.com/VCL/en/StrUtils.PosEx)在*Delim1`的位置之后搜索`Delim2`. (16认同)

Arn*_*hez 12

如果第二个文本也出现在第一个模式之前,上述功能将不起作用...

您应该使用PosEx()而不是Pos():

你可以使用Pos和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;
Run Code Online (Sandbox Code Playgroud)


Dav*_*nan 10

我会做这样的事情:

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;
Run Code Online (Sandbox Code Playgroud)


小智 7

得到他们所有

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;
Run Code Online (Sandbox Code Playgroud)