Split directory and file name from a path in Clojure
Suppose we have a full path string of a file like this
c:\dir1\dir2\file.pdf
We want to split it to two parts: directory path and file name
c:\dir1\dir2 and file.pdf
Its a pretty common task in administration programming. There are a lot of ways to accomplish it. Now consider how to do it in Clojure. First the file name part can be matched with a regular expression, what we need to match is from the last back slash to the end of the string. Here is the regular expression.
"\\([^\\]*$)"
This regular expression says matching start from a back slash and any number of characters that is not a back slash to the end.
Clojure provided a function re-find to match a string with regular expression, lets see what it output:
(re-find #"\\([^\\]*$)" "c:\\dir1\\dir2\\file.pdf") ["\\file.pdf" "file.pdf"]
Now we want to match all the rest substring that not part of the file name part, we can construct a regular expression based on the first one.
"(.*)\\[^\\]*" (re-find #"(.*)\\[^\\]*" "c:\\dir1\\dir2\\file.pdf") ["c:\\dir1\\dir2\\file.pdf" "c:\\dir1\\dir2"]
With the two regular expression, the function is easy to write:
(defn split-fileloc-file [file] (let [re #"\\([^\\]*$)" re-others #"(.*)\\[^\\]*" ] {:fileloc (second (re-find re-others file)) :file (second (re-find re file))} ) ) (split-fileloc-file "c:\\dir1\\dir2\\file.pdf") {:fileloc "c:\\dir1\\dir2", :file "file.pdf"}
Clojure
Clojure Internals