Regular expression to match a valid absolute Windows directory containing spaces

Here's a regex that will work:

^[a-zA-Z]:\\(((?![<>:"/\\|?*]).)+((?<![ .])\\)?)*$

It makes the path conform to the NTFS standard (see the MSDN spec). I'll break it down:

^[a-zA-Z]:\\ matches single drive letter, with colon and backslash

(?![<>:"/\\|?*]) is a negative lookahead to ensure the next character is not invalid

((?![<>:"/\\|?*]).)+ wraps that lookahead, followed by the next character, any number of times

(?<![ .])\\ is a negative lookbehind to ensure the file/directory doesn't end with a space or period. Please note: Lookbehinds are not fully implemented everywhere just yet.

All of that is is repeated 0 to many times, with the last backslash optional.

For many use cases it may be best to restrict the path length to 256 characters. To do so, replace *with {0,256}.

EDIT: allow root directory

Tags:

Regex