BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
yichentian226
Obsidian | Level 7

Hi,

I am trying to extract the characters before the second "-" in the value (name is pagepath). Any ideas or thoughts are appreciated! 

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
Astounding
PROC Star

This should work:

want = catx('-', scan(string, 1, '-'), scan(string, 2, '-') );

View solution in original post

9 REPLIES 9
yichentian226
Obsidian | Level 7

Thanks for the reply, I used scan function and I could extract characters before the first "-", but I'm not sure how to extract characters before the second "-". Here's an example, abc-def-ghi, I want to get result as "abc-def". 

Reeza
Super User

Show your code. What did you put as the second and third parameters?

 

SCAN(stringcount <, character-list <, modifier>>)

 

 

 

 

mklangley
Lapis Lazuli | Level 10

@yichentian226   Here's one way to do it:

data have;
    input pagepath $25.;
    datalines;
    abc-def-ghi-jkl
    testing-it-again
    ;
run;

data want (drop=p i);
    set have;
    p = 0;
    do i=1 to 2 until(p=0); 
        p = find(pagepath, '-', p+1);
    end;
    if p ne 0 then str_before_2nd_hyphen = substr(pagepath, 1, p-1);
run;

Reference:  https://blogs.sas.com/content/sgf/2019/06/26/finding-n-th-instance-of-a-substring-within-a-string/

yichentian226
Obsidian | Level 7

Thanks it's great! Very helpful

jimbarbour
Meteorite | Level 14

Program:

data Have;
	DROP	Second_Dash_Position;
	DROP	String_Length;
	LENGTH	With_Dashes	$35;
	INPUT	With_Dashes	$;
	Second_Dash_Position	=	FIND(With_Dashes, '-', (INDEX(With_Dashes, '-') + 1));
	String_Length			=	LENGTH(With_Dashes)	-	(LENGTH(With_Dashes)	-	Second_Dash_Position) - 1;
	IF	Second_Dash_Position	THEN
		Before_the_Dashes	=	SUBSTR(With_Dashes, 1, String_Length);
datalines;
happy-go-lucky
fleet-of-foot
down-in-the-mouth
woe-begone
fine-and-dandy
In-like-Flynn
The-more-the-merrier
;
RUN;

Results:

jimbarbour_0-1600889354261.png

 

Jim

Astounding
PROC Star

This should work:

want = catx('-', scan(string, 1, '-'), scan(string, 2, '-') );
yichentian226
Obsidian | Level 7

I really like your way of solving it! Thanks it's great 🙂

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—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
  • 9 replies
  • 7244 views
  • 8 likes
  • 5 in conversation