DATA Step, Macro, Functions and more

Extract numeric parts from a string

Accepted Solution Solved
Reply
Contributor
Posts: 73
Accepted Solution

Extract numeric parts from a string

I have a character variable that takes on the following values.

 

A 111 C111

AB 1234 D311

A/B AA A1212

BC 123 D123

CSA JJK P00

 

I would like to grab the number between the first and second space, if that part is indeed a number. I would like to get:

111

1234

.

123

.

 

How can I achieve this? Thanks.


Accepted Solutions
Solution
‎10-16-2017 10:42 AM
Frequent Contributor
Posts: 89

Re: Extract numeric parts from a string

Posted in reply to apolitical

You can use the scan function to find the second word, when a blank space is the delimiter between words.  Use the input function to convert that second word to a number.

 

data have;
  length char_string $ 25;
  input char_string $25. ;
  datalines;
A 111 C111
AB 1234 D311
A/B AA A1212
BC 123 D123
CSA JJK P00
  ;
run;

proc print data=have;
run;

data want;
  set have;
  middle_number=input(scan(char_string,2,' '),12.);
run;

proc print data=want;
run;

View solution in original post


All Replies
Solution
‎10-16-2017 10:42 AM
Frequent Contributor
Posts: 89

Re: Extract numeric parts from a string

Posted in reply to apolitical

You can use the scan function to find the second word, when a blank space is the delimiter between words.  Use the input function to convert that second word to a number.

 

data have;
  length char_string $ 25;
  input char_string $25. ;
  datalines;
A 111 C111
AB 1234 D311
A/B AA A1212
BC 123 D123
CSA JJK P00
  ;
run;

proc print data=have;
run;

data want;
  set have;
  middle_number=input(scan(char_string,2,' '),12.);
run;

proc print data=want;
run;
Frequent Contributor
Posts: 89

Re: Extract numeric parts from a string

Posted in reply to SuzanneDorinski

That code will show notes in the log, when the second word has letters.  To prevent those notes in the log, you can test to see if there are any letters in the second word before converting it to a number.

 

  if anyalpha(scan(char_string,2,' '))=0 then
    middle_number=input(scan(char_string,2,' '),12.);
Respected Advisor
Posts: 4,173

Re: Extract numeric parts from a string

Posted in reply to SuzanneDorinski

@SuzanneDorinski

Another way to suppress these warnings: Use the ?? argument with the input function.

 

data want;
  set have;
  middle_number=input(scan(char_string,2,' '),?? best32.);
run;

 

Contributor
Posts: 73

Re: Extract numeric parts from a string

Posted in reply to SuzanneDorinski
Works well. Thank you!
☑ This topic is solved.

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

Discussion stats
  • 4 replies
  • 206 views
  • 1 like
  • 3 in conversation