using %REPLACE to Scan Replace in RPG

UPDATE 2017 : USE %SCANRPL Built in Function – IBM added a %BIF to do this for us in modern RPGLE so we can now just do a %SCANRPL in native RPG. I’m leaving this old blog here for reference but look HERE for the modern and much much easier way of doing this schnizzle



So, You still want to see how to SCAN REPLACE in RPG the old fashioned way?

What’s the easiest way?

Using the %REPLACE built in Function is easy and efficient although code wise its a little cumbersome:

// Update email address 
Dow %Scan('L#EMAIL': %TRIMR(SrcDta )) > *Zeros; 
 SrcDta = %Replace(%trimr(ParmEmail) 
        :%Scan('L#EMAIL' : %TRIMR(SrcDta ))

In this example, I am scanning a program variable (SRCDTA) looking for any occurence of the word “L#EMAIL” and replacing it with the contents of “PARMEMAIL”. The email value is %TRIM’ed which means that any blanks at the end of the email address are ignored.

So, to change this to work for you

  1. Change the value of L#EMAIL to the value that you want to be replaced
  2. Change the value of SRCDTA to the field name that you want to scan
  3. Change the value of PARMEMAIL to the new value that you want to replace every occurrence of “L#EMAIL”

Hope it helps…

If you are using the PROJEX4I Power Tools:

I use a similar process in the PROJEX Service Program and then you can easily run a SCAN/REPLACE on a single line of RPG code.

So lets say I wanted to scan for the word ‘bob’ and change it for the word ‘Fred’ within a string i could do it like this using this Prototype:

myVariable = #Scanreplace ( : 'bob' : 'Fred' )

Much simpler than using the complex %REPLACE BIF I’m sure you will agree.

Here’s the Prototype:

  // +-------------------------------------------------------------------+ 
 // | #ScanReplace - Scan a string and replace stuff in it |
 // +-------------------------------------------------------------------+ 
 dcl-proc #ScanReplace export;
 dcl-pi #ScanReplace like($bigvariable);
 ParmSource like($bigvariable) const;
 OldString varchar(1024) const;
 NewString varchar(1024) const;
 dcl-s $ScanReplace like($bigvariable);
 dcl-s $Found int(10);
 dcl-s $Replace int(10);
 $ScanReplace = ParmSource;
 $Found = %scan(%trimr(OldString):$ScanReplace);
 dow $Found > 0;
 $ScanReplace = %replace(%trimr(NewString):$ScanReplace
 $Replace = $Found + %len(NewString);
 $Found = %scan(%trimr(OldString):$ScanReplace:$Replace);
 Return $ScanReplace;

Obviously you will also need the Procedure which looks like this:

  // +--------------------------------------------------------+
 // | #ScanReplace - Scan the string and replace stuff in it |
 // +--------------------------------------------------------+
 dcl-pr #ScanReplace like($bigvariable) extproc(*cl:'#SCANREPLACE');
 *n like($bigvariable) const; // ParmSource
 *n varchar(1024) const; // OldString
 *n varchar(1024) const; // NewString