BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
madhustats
Calcite | Level 5

Hi,

 

I have a string and I want to remove last word with length one or two.

 

Example 1: Input: EXPERTS INTERNATIONAL RECRUITMENT S --------Output: EXPERTS INTERNATIONAL RECRUITMENT

 

Example 2: Input: LOOTAH BUILDING CONSTRUCTION LL -----------Output: LOOTAH BUILDING CONSTRUCTION

 

 

Please help.

1 ACCEPTED SOLUTION

Accepted Solutions
Patrick
Opal | Level 21

In below code the RegEx for want1 just removes the last term, the RegEx for want2 only removes the last term if it has 1 or 2 characters.

data sample;
  infile datalines truncover;
  input have $80.;
  length want1 want2 $80;
  want1=prxchange('s/\b\w+$//',1,strip(have));
  want2=prxchange('s/\b\w{1,2}$//',1,strip(have));
  datalines;
EXPERTS INTERNATIONAL RECRUITMENT S 
LOOTAH BUILDING CONSTRUCTION LL
LOOTAH BUILDING CONSTRUCTION LLS
;
proc print data=sample;
run;

Patrick_0-1676533747616.png

 

View solution in original post

3 REPLIES 3
andreas_lds
Jade | Level 19

If the last word is longer than two chars it should not be removed, right?

Are words separated by blanks only?

 

If both assumptions are true, then i would use:

  • b = findc(trim(string), ' ', 'b') to find the position of the last blank
  • calculate the difference between b and the length of the string,
  • if the result is smaller than 3: substr to extract anything before b
Patrick
Opal | Level 21

In below code the RegEx for want1 just removes the last term, the RegEx for want2 only removes the last term if it has 1 or 2 characters.

data sample;
  infile datalines truncover;
  input have $80.;
  length want1 want2 $80;
  want1=prxchange('s/\b\w+$//',1,strip(have));
  want2=prxchange('s/\b\w{1,2}$//',1,strip(have));
  datalines;
EXPERTS INTERNATIONAL RECRUITMENT S 
LOOTAH BUILDING CONSTRUCTION LL
LOOTAH BUILDING CONSTRUCTION LLS
;
proc print data=sample;
run;

Patrick_0-1676533747616.png

 

RW9
Diamond | Level 26 RW9
Diamond | Level 26

You could simply scan the last word by space, and check if length is 1 or 2:

data want;
  str="abc ert werty we";
  if lengthn(scan(str,-1," ")) in (1,2) then check=1;
run;

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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