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

How to search and replace in RichEdit

By Zarko Gajic, About.com

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

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

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

Easy ways to connect two computers for networking purposes. 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.