## Extract numeric parts from a string

Solved
Frequent Contributor
Posts: 91

# 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: 115

## Re: Extract numeric parts from a string

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;``````

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

## Re: Extract numeric parts from a string

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: 115

## Re: Extract numeric parts from a string

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.);
``````
Posts: 4,685

## Re: Extract numeric parts from a string

@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;``````

Frequent Contributor
Posts: 91