How to Use PRXCHANGE Function in SAS (With Examples)


You can use the PRXCHANGE function in SAS to replace a specific pattern in a string.

This function uses the following basic syntax:

PRXCHANGE(regular expression, times, source)

where:

  • regular expression: Regular expression that specifies the pattern to search for
  • times: The number of times to replace to search for and replace the pattern (use -1 to continue to replace pattern until end of source is reached)
  • source: Name of the variable to search

The following examples show two common ways to use this function in practice with the following dataset in SAS:

/*create dataset*/
data my_data;
    input phrase $char40.;
    datalines;
This is a cool name
That is a cool cool zebra
Oh hey there
Oh cool it's a cool-looking dog
Well now that is COOL
;
run;

/*view dataset*/
proc print data=my_data;

Example 1: Use PRXCHANGE to Replace Pattern in String with New Pattern

The following code shows how to use the PRXCHANGE function to create a new column called new_phrase that replaces each occurrence of “cool” with “fun” in the phrase column:

/*create new dataset*/
data new_data;
    set my_data;
    new_phrase = prxchange('s/cool/fun/i', -1, phrase);
run;

/*view new dataset*/
proc print data=new_data;

Notice that each occurrence of “cool” has been replaced with “fun” instead.

Note that we used s in the regular expression to specify that we wanted to perform a substitution and we used i to specify that it should be case-insensitive.

Example 2: Use PRXCHANGE to Replace Pattern in String with Blank

The following code shows how to use the PRXCHANGE function to create a new column called new_phrase that replaces each occurrence of “cool” with a blank in the phrase column:

/*create new dataset*/
data new_data;
    set my_data;
    new_phrase = prxchange('s/cool//i', -1, phrase);
run;

/*view new dataset*/
proc print data=new_data;

Notice that each occurrence of “cool” has been replaced with a blank.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Extract Numbers from String in SAS
How to Remove Commas from String in SAS
How to Split Strings by Delimiter in SAS

Featured Posts

Leave a Reply

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