首页  编辑  

查找和替换文字而不丢失格式

Tags: /超级猛料/VCL/Memo&Edit&Richedit/RichEdit、RxRichEdit/   Date Created:

查找RichEdit中的文字并替换,而不丢失其原来的富文本格式:

function Search_And_Replace(RichEdit: TRichEdit;

 SearchText, ReplaceText: string): Boolean;

var

 startpos, Position, endpos: integer;

begin

 startpos := 0;

 endpos := Length(RichEdit.Text);

 RichEdit.Lines.BeginUpdate;

 while RichEdit.FindText(SearchText, startpos, endpos, [stMatchCase]) <> -1 do

   begin

     endpos   := Length(RichEdit.Text) - startpos;

     Position := RichEdit.FindText(SearchText, startpos, endpos, [stMatchCase]);

     startpos := Position + Length(ReplaceText);

     RichEdit.SetFocus;

     RichEdit.SelStart  := Position;

     RichEdit.SelLength := Length(SearchText);

     RichEdit.ClearSelection;

     RichEdit.SelText := ReplaceText;

   end;

 RichEdit.Lines.EndUpdate;

end;

procedure TForm1.Button1Click(Sender: TObject);

var

 ms: TMemoryStream;

begin

 ms := TMemoryStream.Create;

 try

   RichEdit1.Lines.SaveToStream(ms) ;

   ms.Seek(0, soFromBeginning) ;

   RichEdit2.Lines.LoadFromStream(ms) ;

 finally

   ms.Free;  // don't forget to free your objects

 end;

 Search_And_Replace(RichEdit2, '.', '.'+#13#10);

 Search_And_Replace(RichEdit2, '\\', #13#10 );

end;