gpt4 book ai didi

Delphi - 在标签之间提取字符串(重复标签)

转载 作者:行者123 更新时间:2023-12-03 18:13:43 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来提取两个标签之间的字符串。问题是第一个标签在该字符串中是重复的,计数未知,例如

Str := 'Delphi App Hello Hello SomeText here Hello Hello Hello This is a Test!';

我真正想要的是 extract Hello This is a Test!

  • TagF 是最后一个Hello
  • TagL 是测试!

TagF 的重复计数是随机的。

Function sExtractBetweenTagsB(Const s, LastTag, FirstTag: string): string;
var
i, f : integer;
sTemp : string;
begin
sTemp := s;
repeat
Delete(sTemp,Pos(FirstTag, sTemp),length(FirstTag));
until AnsiPos(FirstTag,sTemp) = 0;
f := Pos(LastTag, sTemp);
Result:= FirstTag+' '+Copy(sTemp, 1, length(sTemp));
end;

输出是:

Hello Delphi App   SomeText here    This is a Test!

最佳答案

您可以使用 PosEx函数扫描您的字符串以查找标签并向前查找:

program SO30827180;

{$APPTYPE CONSOLE}

{$R *.res}

uses
SysUtils,
StrUtils;

function ExtractString(const Input : String; const TagF: String; const TagL : String) : String;

var
LastPos : Integer;
NewPos : Integer;

begin
Result := '';
NewPos := Pos(TagF, Input);
if NewPos <> 0 then
begin
LastPos := NewPos;
// scan to last start tag
while true do
begin
NewPos := PosEx(TagF, Input, NewPos+1);
if NewPos <> 0 then
LastPos := NewPos
else
Break;
end;
// now seek end tag, starting from last starting tag position
NewPos := PosEx(TagL, Input, LastPos+1);
if NewPos <> 0 then
Result := Copy(Input, LastPos, NewPos-LastPos+Length(TagL));
end;
end;

var
Line : String;

begin
Line := 'Delphi App Hello Hello SomeText here Hello Hello Hello This is a Test!';
Writeln(Format('Input: "%s"', [Line]));
Writeln(Format('Ouput: "%s"', [ExtractString(Line, 'Hello', 'Test!')]));
Line := ' Test! Delphi App Hello Hello SomeText here Hello Hello Hello This is a Test! Some end chars';
Writeln(Format('Input: "%s"', [Line]));
Writeln(Format('Ouput: "%s"', [ExtractString(Line, 'Hello', 'Test!')]));
Readln;
end.

示例输出:

Input: "Delphi App Hello Hello SomeText here Hello Hello Hello This is a Test!"
Ouput: "Hello This is a Test!"
Input: " Test! Delphi App Hello Hello SomeText here Hello Hello Hello This is a Test! Some end chars"
Ouput: "Hello This is a Test!"

关于Delphi - 在标签之间提取字符串(重复标签),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com