DATA Step, Macro, Functions and more

String manipulation

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 10
Accepted Solution

String manipulation

Hi all I am new to sas.

I hope you can help.

I am trying to break up a strings to receive the last group of digits contained within the string.

Eg1 my string
"#113#468#9999#2474#.#.#.#.#"

Result
2474

Eg2

"5743#788#1#9#89999#64#68#.#.#"

Result
68

Thanks in advance.

Accepted Solutions
Solution
‎04-30-2018 06:08 AM
Super User
Super User
Posts: 9,599

Re: String manipulation

Well:

data want;
  set have;
  do i=1 to countw(mystring,"#");
if scan(mystring,i,"#") ne "." then last_num=scan(mystring,i,"#");
end;
run;

View solution in original post


All Replies
Occasional Contributor
Posts: 10

Re: String manipulation

Note the last character could be a number or a .
Respected Advisor
Posts: 4,736

Re: String manipulation

@Go210

Below should do the job.

data have;
  length string $100;
  string="#113#468#9999#2474#.#.#.#.#";output;
  string="5743#788#1#9#89999#64#68#.#.#";output;
  string="#.#.#";output;
  string="#.#.#123";output;
  string="456#.#.#";output;
run;

data want;
  set have;
  number=input(scan(string,-1,,'kd'),best32.);
run;
Solution
‎04-30-2018 06:08 AM
Super User
Super User
Posts: 9,599

Re: String manipulation

Well:

data want;
  set have;
  do i=1 to countw(mystring,"#");
if scan(mystring,i,"#") ne "." then last_num=scan(mystring,i,"#");
end;
run;
PROC Star
Posts: 1,283

Re: String manipulation

are your digits always surrounded by ##? 

PROC Star
Posts: 1,283

Re: String manipulation

An alternative..

 

data have;
    length string $100;
    string="#113#468#9999#2474#.#.#.#.#";output;
    string="5743#788#1#9#89999#64#68#.#.#";output;
run;

data want;
    set have;

    to=anydigit(string, -length(string));
    from=notdigit(string, -to)+1;

    num=substr(string, from, to-from+1);
run;
Occasional Contributor
Posts: 10

Re: String manipulation

Thanks for all your help. So many solutions!

PROC Star
Posts: 1,803

Re: String manipulation

No loop needed for your examples, very simple and straight forward-->

data want;
mystring="#113#468#9999#2474#.#.#.#.#";
last_num=scan(compress(mystring,'.'),-1,'#');
output;
mystring="5743#788#1#9#89999#64#68#.#.#";
last_num=scan(compress(mystring,'.'),-1,'#');
output;
run;
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 7 replies
  • 157 views
  • 1 like
  • 5 in conversation