Windows Path Validation Regular Expression
Windows file system paths use backslashes as separators and start with a drive letter followed by a colon. Path components cannot contain certain reserved characters: \ / : * ? " < > |. This regex validates Windows path formats according to Windows file naming conventions. For Unix/Linux paths, see the Unix path validation article.
Recommended Solution
Explanation
^- Start of the string.[a-zA-Z]- Drive letter (A-Z, case-insensitive).:- Colon after drive letter.\\- Backslash (escaped in regex).(?:[^\\/:*?"<>|\r\n]+\\)*- Zero or more directory names:[^\\/:*?"<>|\r\n]+- One or more valid characters (excluding reserved characters).\\- Followed by a backslash.
[^\\/:*?"<>|\r\n]*- Optional file or final directory name (no trailing backslash required).$- End of the string.
Notes
- This regex validates the format of Windows paths but does NOT verify if the path exists on the filesystem.
- Reserved characters that cannot appear in file/folder names:
\ / : * ? " < > | - This pattern does not validate UNC paths (network paths like \\\\server\\share). Modify the pattern to support UNC if needed.
- Windows has reserved file names (CON, PRN, AUX, NUL, COM1-9, LPT1-9) which are not validated by this regex.
- Maximum path length in Windows is typically 260 characters (MAX_PATH), but this is not enforced by this regex.
- Spaces are allowed in path components, which is common in Windows paths (e.g., "Program Files").
- This pattern requires backslashes. Paths with forward slashes (sometimes accepted by Windows APIs) will not match.
- For more robust path validation, use filesystem APIs like
System.IO.Pathin .NET or similar in other languages.
Implementation
Test Cases
| Path | Type | Valid |
|---|---|---|
| C:\\ | Root directory | |
| C:\\Windows\\System32 | Absolute path | |
| D:\\Users\\Documents\\file.txt | File path | |
| E:\\Program Files\\Application | Path with spaces | |
| F:\\folder\\subfolder\\ | Trailing backslash | |
| Z:\\data | Z drive | |
| C:\\path-with-dashes\\file_name.ext | Dashes and underscores | |
| C:\\Windows | Simple path | |
| C:\\Users\\admin\\Desktop\\file.docx | Document path | |
| /unix/style/path | Unix path | |
| C:/forward/slash | Forward slashes | |
| C:\\invalid*name | Contains asterisk | |
| C:\\invalid?name | Contains question mark | |
| C:\\invalid<>name | Contains angle brackets | |
| C:\\invalid|name | Contains pipe | |
| C:\\invalid:name | Contains colon | |
| invalid\\path | Missing drive letter | |
| (empty string) | Empty string | |
| C: | Drive letter only | |
| 1:\\path | Invalid drive letter |