8.22. Extract the Folder from a Windows Path

Problem

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 \folder\subfolder\ from c:\folder\subfolder\file.ext or \\server\share\folder\subfolder\file.ext.

Solution

^([a-z]:|\\\\[a-z0-9_.$-]+\\[a-z0-9_.$-]+)?((?:\\|^)↵
(?:[^\\/:*?"<>|\r\n]+\\)+)
Regex options: Case insensitive
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Discussion

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, ^([a-z]:|\\\\[a-z0-9_.$-]+\\[a-z0-9_.$-]+)?, 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 8.20, and the second alternative matches the server and share in UNC paths, as in Recipe 8.21. Recipe 2.8 explains the alternation operator.

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

Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.