SQR: Function to Remove Special Characters

remove special characters function in SQRLast week we were discussing about a piece of code that would remove special characters from a string. This was used in an SQR that writes to a .csv file.

This week we had a requirement for more than half a dozen of such SQRs.

It was part of converting some SQL queries into SQR so that they could be scheduled overnight.

So I went in for a function that would serve the purpose.

A procedure (function) that removes special characters from a string. Here is how to use it.

Do SPL-REMOVE (&descr, $descr)

Here, &descr is the input parameter and may contain any number of special characters.

The procedure returns the string without any special characters as $descr.

!Procedure for removing special characters from a string
!Here we use the ideology that we have a finite set of
!valid characters (alphanumeric) while the set of special
!characters is fairly big.
 
!***********************************************************************!
! Procedure: 	SPL-REMOVE
! Desc: Removes special characters from the source string - $srcstr.
!	The output will be stored in the $outputstr
!	To use this procedure use: Do SPL-REMOVE($Source, $outputstr)
!***********************************************************************!
BEGIN-PROCEDURE SPL-REMOVE($srcstr, :$outputstr)
 
LET $valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz -.:/0123456789@()=+%*"£$'
LET $invalid_chars = translate($srcstr, $valid_chars, '')
LET #invalid = length($invalid_chars)
 IF #invalid
  LET $outputstr = translate($srcstr, $invalid_chars, '')
ELSE
 LET $outputstr = $srcstr
END-IF
 
END-PROCEDURE
!***********************************************************************!

You can download the code here.

Tags: , ,
Leave a Reply

Your email address will not be published. Required fields are marked *

*
*