2008. augusztus 21., csütörtök

How to check if the caret position in a TMemo is between two HTML tags


Problem/Question/Abstract:

I need a string procedure that checks whether the caret position is between the tags '<>' , and if this is true, the contents of the tag are placed in a string for further processing.

Answer:

Something like this:

function FindTextBetweenTags(const S: string; caretpos: Integer): string;
var
  nStart, nEnd: Integer;
begin
  Result := EmptyStr;
  {caretpos is 0-based, string indices are 1-based}
  Inc(caretpos);
  {move backwards from caretpos util we find a '<'}
  nstart := caretpos;
  while ((nstart > 0) and (S[nstart]) <> '<') do
    Dec(nstart);
  if nstart = 0 then
    Exit;
  {move to first char after '<'}
  Inc(nstart);
  if S[nstart] = '>' then
    Exit; {empty tag}
  {move forward until we find a '>'}
  nend := nstart;
  while (nend <= Length(S)) and (S[nend] <> '>') do
    Inc(nend);
  if (nend > Length(S)) or (nend <= caretpos) then
    Exit;
  Result := Copy(S, nstart, nend - nstart);
end;

You would call it like

tagstring := FindtextBetweentags(memo1.text, memo1.selstart);

Nincsenek megjegyzések:

Megjegyzés küldése