2009. február 20., péntek

How to remove blocks of text


Problem/Question/Abstract:

Never needed to remove blocks of text delimited by words or place holders from a text? Or comments, included in brackets, from a string? Here is a useful function that does that.

Answer:

Just use this function to remove text between round brackets, or specify a different start/end placeholder to remove what you nees.

function RemoveBlocks(Value: string; BeginWidth: string = '('; EndWith: string = ')'):
  string;
var
  BeginPoint: Integer;
  EndPoint: Integer;
begin
  BeginPoint := Pos(BeginWith, Value);
  EndPoint := Pos(EndWith, Value);
  while ((BeginPoint > 0) and (EndPoint > BeginPoint)) do
  begin
    Delete(Value, BeginPoint, (EndPoint - BeginPoint + 1));
    BeginPoint := Pos(BeginWith, Value);
    EndPoint := Pos(EndWith, Value);
  end;
  Result := Value;
end;

For example, you can remove all paragraphs in a HTML source just using this:

MyHTML := RemoveBlocks(MyHTML, '<', '>');

You can also improve the function by adding a "case-insensitive" function with something like this:

function RemoveBlocks(Value: string; BeginWidth: string = '('; EndWith: string = ')'):
  string;
var
  BeginPoint: Integer;
  EndPoint: Integer;
begin
  BeginWith := LowerCase(BeginWith);
  EndWith := LowerCase(EndWith);
  BeginPoint := Pos(BeginWith, LowerCase(Value));
  EndPoint := Pos(EndWith, LowerCase(Value));
  while ((BeginPoint > 0) and (EndPoint > BeginPoint)) do
  begin
    Delete(Value, BeginPoint, (EndPoint - BeginPoint + 1));
    BeginPoint := Pos(BeginWith, LowerCase(Value));
    EndPoint := Pos(EndWith, LowerCase(Value));
  end;
  Result := Value;
end;

Nincsenek megjegyzések:

Megjegyzés küldése