Subscribe Bookmark RSS Feed

Regex to pull file from path with JSL

drblove

Contributor

Joined:

Nov 2, 2016

I am sure this is a straightforward answer to this question, but if I have the following:

 

full_path[i] = "C:\dir1\dir2\dir3\dir4\file.xlsx"

and I want to get just "file.xlsx" and the directory depth is variabile, i.e. maybe 2 directories maybe 5, how would I do it?  In Perl I would split the string into an array by the \ and grab the last part of the array, but not sure how to do this in JSL.  Any help would be appreciated!

1 ACCEPTED SOLUTION

Accepted Solutions
brady_brady

Staff

Joined:

Jun 9, 2012

Solution

word ( -1, full_path[i], "\" )

 

You can use negative values, in the word() function, so -1 gives the last word, using the delimiter of choice.

 

 

5 REPLIES
melaniedrake

Staff

Joined:

May 30, 2014

You can use the JSL function Words() to separate a path into its component part, and then take just the last piece. Example:

 

full_path = {"C:\dir1\dir2\dir3\dir4\file.xlsx"}; i = 1; // setup

full_path[i] = "C:\dir1\dir2\dir3\dir4\file.xlsx";

filename = Words(full_path[i], "\"); // separate the path based on the backslash as a delimiter - returns a list

filename = filename[N Items(filename)]; // get the last string in the list

 

/*:

"file.xlsx"

Jeff_Perkinson

Community Manager

Joined:

Jun 23, 2011

Try the Words() function

 

full_path = "C:\dir1\dir2\dir3\dir4\file.xlsx";

listofwords=words(full_path, "\");

filename=listofwords[nitems(listofwords)];

/*:

"file.xlsx"

 

-Jeff
ms

Super User

Joined:

Jun 23, 2011

Two examples of how it could be done:

full_path = "C:\dir1\dir2\dir3\dir4\file.xlsx";

//Regex (fails if filename contains non-word characters)
file1 = Regex(full_path, "[\w.]+$"); 
// Split string
file2 = Reverse(Words(full_path, "\"))[1];

Show(file1, file2);
brady_brady

Staff

Joined:

Jun 9, 2012

Solution

word ( -1, full_path[i], "\" )

 

You can use negative values, in the word() function, so -1 gives the last word, using the delimiter of choice.

 

 

drblove

Contributor

Joined:

Nov 2, 2016

This is a great solution, one line.  Thank you very much!