SAS (Base SAS)+
*==============================================================================;
* Step 1: create a small dataset with messy text values ;
*==============================================================================;
data compress01;
infile datalines dlm='|' dsd truncover;
length raw_text $40;
input id raw_text $;
datalines;
1|SUBJ 001
2|SUBJ-002/A
3| AE-TERM 123
4|VISIT 01 / DAY 5
5|ABC@123#XYZ
6| 2024-01/15
;
run;
*==============================================================================;
* Step 2: apply several COMPRESS variations ;
*==============================================================================;
data compress02;
set compress01;
no_spaces = compress(raw_text); /* default: drops blanks only */
no_whitespace = compress(raw_text, , "s"); /* "s" modifier: any whitespace */
no_dash_slash = compress(raw_text, "-/"); /* drop listed characters */
digits_only = compress(raw_text, , "kd"); /* k=keep, d=digits */
alnum_only = compress(raw_text, , "kad"); /* k=keep, a=alpha, d=digits */
run;- To drop only blank spaces, we call
compresswith just the first argument — for example,compress(string). - This is the default behaviour and is often enough when the only clutter in our text is ordinary spaces.
- If we want to remove a specific list of characters instead, we pass them as the second argument.
- For example,
compress(string, "-/")drops every hyphen and slash it finds. - The second argument is plain character matching, not a regular expression.
- When we need something broader — like “drop all whitespace” or “drop all punctuation” — SAS offers single-letter modifiers in the third argument.
- The useful ones are
d(digits),a(alphabetic),s(whitespace),p(punctuation). - We add the
kmodifier to flip the meaning from “drop these” to “keep these”. - So
"kd"keeps digits and drops everything else. - And
"kad"keeps letters and digits, drops everything else. - One gotcha: bare
compress()strips ordinary blanks but not tabs. - If the upstream file might contain tabs or newlines, we add the
smodifier.