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

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

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.Path in .NET or similar in other languages.

Implementation

const windowsPathRegex = /^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$/;
const isValidWindowsPath = (path) => windowsPathRegex.test(path);

Test Cases

PathValid
C:\
C:\Windows\System32
D:\Users\Documents\file.txt
E:\Program Files\Application
F:\folder\subfolder\
Z:\data
C:\path-with-dashes\file_name.ext
C:\Windows
C:\Users\admin\Desktop\file.docx
/unix/style/path
C:/forward/slash
C:\invalid*name
C:\invalid?name
C:\invalid<>name
C:\invalid|name
C:\invalid:name
invalid\path
(empty string)
C:
1:\path