1. Home
  2. Computing & Technology
  3. Delphi Programming

How to search and replace in RichEdit

By , About.com Guide

The following code snippet will search for a string and replace it with Replacement String in RichEdit. Make sure you have RichEdit1 (TRichEdit) on Form1.

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.RearchAndReplace
           (InSearch, InReplace: string) ;
var X, ToEnd : integer;
    oldCursor : TCursor;
begin
   oldCursor := Screen.Cursor;
   Screen.Cursor := crHourglass;
   with RichEdit1 do
   begin
     X := 0;
     ToEnd := length(Text) ;
     X := FindText(inSearch, X, ToEnd, []) ;
     while X <> -1 do
     begin
       SetFocus;
       SelStart := X;
       SelLength := length(inSearch) ;
       SelText := InReplace;
       X := FindText(inSearch,
                     X + length(InReplace),
                     ToEnd, []) ;
     end;
   end;
   Screen.Cursor := oldCursor;
end;

procedure TForm1.Button1Click(Sender: TObject) ;
var
   SearchText, ReplaceText: string;
begin
   SearchText := 'Pascal';
   ReplaceText := 'Delphi';
   RearchAndReplace(SearchText, ReplaceText) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» What is being typed into the DBGrid?
« Hide caret (text cursor) "inside" TMemo component

Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TMemo, TRichEdit
  6. How to search and replace in RichEdit

©2009 About.com, a part of The New York Times Company.

All rights reserved.