DATA Step, Macro, Functions and more

Extract a number somewhere in a string

Accepted Solution Solved
Reply
Contributor
Posts: 41
Accepted Solution

Extract a number somewhere in a string

[ Edited ]

Hi all,

 

I have a quite long string, with somewhere inside the string: a number, composed by a various number of digits.

I need to extract the complete number.

I am sure that on the right there is at least one character, on the left too.

All characters apart from the number are not digits.

 

Do you know how I can do it?

 

Thanks


Accepted Solutions
Solution
‎02-17-2017 12:04 PM
Contributor
Posts: 30

Re: Extract a number somewhere in a string

Hi

Many different methods. I find prxchange most useful for that:

 

data _null_;

   length num $12;

   str = 'ssfdfsf56789qeqeqd';

   num = prxchange('s/(\D*)(\d*)(\D*)/$2/',-1,str);

   put num=;

run;

View solution in original post


All Replies
Contributor
Posts: 44

Re: Extract a number somewhere in a string

Can you show us your data or if not replicate a dummy of it ?

Solution
‎02-17-2017 12:04 PM
Contributor
Posts: 30

Re: Extract a number somewhere in a string

Hi

Many different methods. I find prxchange most useful for that:

 

data _null_;

   length num $12;

   str = 'ssfdfsf56789qeqeqd';

   num = prxchange('s/(\D*)(\d*)(\D*)/$2/',-1,str);

   put num=;

run;

Trusted Advisor
Posts: 1,300

Re: Extract a number somewhere in a string

setting assurances for matching the whole string would be better, on the off change more that one string of numbers happens to occur in a row of the data.

 

num = prxchange('s/^\D+(\d+)\D+$/$1',1,str);

also, since OP states there is definitely at least one char to left and right, can use + instead of * to further validate expected input.

Super User
Posts: 10,500

Re: Extract a number somewhere in a string

Does your data have date values along with the number string you are searching for?

How about identifiers that may include digits such as Highway 66, addresses, telephone numbers or similar?

Super User
Posts: 5,083

Re: Extract a number somewhere in a string

Since you simply want all the digits, a suitably simple approach would be:

 

num = compress(long_string, , 'kd');

 

k = keep

d = digits

☑ This topic is SOLVED.

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

Discussion stats
  • 5 replies
  • 196 views
  • 3 likes
  • 6 in conversation