DATA Step, Macro, Functions and more

replace special characters with a blank character.

Reply
Frequent Contributor
Posts: 77

replace special characters with a blank character.

I want to know how to replace special characters with a blank character.

In the following example, all special characters ; - / * ^ ) in String1 are replaced by a blank character and output as String2

String1 = YT;-/*ADD^)M
String2 = YT____ADD__M

I used _ in String2 to represent a blank character.
N/A
Posts: 0

Re: replace special characters with a blank character.

data x;
String1 = 'YT;-/*ADD^)M';
String2 = translate(String1,' ','`~!@#$%^&*()_+-=[]\{}|;:",./<>?');
put "String1=" String1 / "String2=" String2;
run;


If you have any more special characters to replace, just add a blank to the "to" list in the TRANSLATE function and your special character to the "from" string and all is well. I'm sure there are more elegant ways, but this works.

P.S. if you look at this with, say, SAS code font it shows that the "to" string actually DOES have 32 blanks to match the 32 special characters. Stupid forum. Smiley Very Happy

P.P.S. Not that it matters. You can put in one blank in the "to" string and be fine.
"Values of to and from correspond on a character-by-character basis; TRANSLATE changes the first character of from to the first character of to, and so on. If to has fewer characters than from, TRANSLATE changes the extra from characters to blanks. If to has more characters than from, TRANSLATE ignores the extra to characters."


Message was edited by: mpiehl Message was edited by: mpiehl
Regular Contributor
Posts: 241

Re: replace special characters with a blank character.

Sometimes it is easier to say "anything other than A and B" than to list each and every single thing that is not A or B.




/* convert any non-alphabet chars to a blank */


data _null_;


  v1 = "YT;-/*ADD^)M";


  v2 = prxchange("s/[^A-Z]/ /",-1,v1);


  put (_all_) (=/);


run

Ask a Question
Discussion stats
  • 2 replies
  • 8533 views
  • 2 likes
  • 3 in conversation