UCLA Academic Technology Services HomeServicesClassesContactJobs
Search

SAS FAQ
How can I get rid of extra spaces in a string variable?

Sometimes, a string variable can have many words in it and extra spaces between the words. There might be a need to get rid of the extra spaces for the purpose of nice printing. The example below shows how to use Peal regular expression and some SAS string functions to eliminate the extra spaces. In the example below, variable address and address_s are defined the same way initially. But variable address is then being processed using SAS function prxchange. Function prxchange is associated with function prxparse, which is used to define the string to search and to be replaced with. Roughly, 's/\s+/ /' used below is to say that we want to search for gaps between words with more than one spaces and replace it with one single blank.

data test;
  length address1 $40. address2 $60.;
  input address1 $ 1-20 address2 $ 21-80;
  datalines;
  1234 Washington St     DC          12345
  1234 Irving St         Charlotte  NC      12345
  45 Wall     street     New           York  NY 90454
  ;
  run;
data test2;
  set test;
  address = address1||address2;
  address_s = address1||address2;
  rid = prxparse('s/\s+/ /');
  call prxchange(rid, -1, address);
  drop rid;
run;
proc print data = test2;
run;
Obs         address1         address2                                     address
 1     1234 Washington St    DC          12345               1234 Washington St DC 12345
 2     1234 Irving St        Charlotte  NC      12345        1234 Irving St Charlotte NC 12345
 3     45 Wall     street    New           York  NY 90454    45 Wall street New York NY 90454
Obs                                 address_s
 1     1234 Washington St                      DC          12345
 2     1234 Irving St                          Charlotte  NC      12345
 3     45 Wall     street                      New           York  NY 90454

How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California