7.22. Extract the Folder from a Windows Path
You have a string that holds a (syntactically) valid path to a
file or folder on a Windows PC or network, and you want to extract the
folder from the path. For example, you want to extract
|Regex options: Case insensitive|
Extracting the folder from a Windows path is a bit tricky if we want to support UNC paths, because we can’t just grab the part of the path between backslashes. If we did, we’d be grabbing the server and share from UNC paths too.
The first part of the regex, ‹
skips over the drive letter or the network server and network share
names at the start of the path. This piece of the regex consists of a
capturing group with two alternatives. The first alternative matches
the drive letter, as in Recipe 7.20, and the
second alternative matches the server and share in UNC paths, as in
Recipe 7.21. Recipe 2.8 explains the alternation
The question mark after the group makes it optional. This allows us to support relative paths, which don’t have a drive letter or network share.
The folders are easily matched with ‹
(?:[^\\/:*?"<>|\r\n]+\\)+›. The character class matches a folder name. The noncapturing group matches a folder name ...