删除字符串中的重复文本

removing duplicated text inside a string

我的字符串中有这样的文字

str := 'Hi there My name is Vlark and this is my images <img src=""><img src=""> But This images need to be controlled <img src=""><img src=""><img src=""><img src="">'; 

这个字符串有 6 个图像标签 <img 我想控制这个标签,所以如果这个字符串有超过 3 个图像标签,保留前三个并删除其余图像标签。我不知道如何在编码中做到这一点

策略:

  • 查找完整封闭标签的位置和长度:<img>
  • 如果计数大于 3,删除标签。

function RemoveExcessiveTags( const s: String): String;
var
  tags,cP,p : Integer;
begin
  tags := 0;
  cP := 1;
  Result := s;
  repeat
    cP := Pos('<img',Result,cP);
    if (cP > 0) then begin
     // Find end of tag
      p := Pos('>',Result,cP+4);
      if (p > 0) then begin
        Inc(tags);
        if (tags > 3) then begin // Delete tag if more than 3 tags
          Delete(Result,cP,p-cP+1);
        end
        else
          cP := p+1;  // Next search start position
      end
      else
        cP := 0;  // We reached end of string, abort search
    end;
  until (cP = 0);
end;