How to use PRXCHANGE function in SAS?

The PRXCHANGE function in SAS is used to perform pattern matching and replacement in strings. It is a powerful tool that can be used to search for and replace substrings in a given string. This tutorial provides an overview of the PRXCHANGE function, including its syntax, parameters, and examples of its use in SAS.


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.

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

x