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-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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