Regex to Match Windows File Paths

Validate Windows file paths with this regex. Matches paths like C:\Users\name\file.txt with drive letter prefix. Free regex tester.

Regular Expression

/^[a-zA-Z]:\\(?:[\w.-]+\\)*[\w.-]*$/

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
[a-zA-Z]Character class — matches any one of: a-zA-Z
:Matches the literal character ':'
\\Escaped character '\'
(?:Start of non-capturing group
[\w.-]Character class — matches any one of: \w.-
+Matches the preceding element one or more times (greedy)
\\Escaped character '\'
)End of group
*Matches the preceding element zero or more times (greedy)
[\w.-]Character class — matches any one of: \w.-
*Matches the preceding element zero or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex validates Windows file paths with drive letter prefixes. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string.

[a-zA-Z] — A character class matching a single letter (upper or lowercase) for the drive letter. Windows drives are typically C:, D:, E:, etc.

: — Matches the literal colon after the drive letter.

\ — Matches a literal backslash. In regex, a single backslash is an escape character, so two backslashes are needed to match one literal backslash. In a JavaScript string, this would be written as four backslashes.

(?: — Opens a non-capturing group for directory segments.

[\w.-]+ — Matches one or more valid filename characters: word characters (letters, digits, underscore), dots, and hyphens.

\ — Matches the literal backslash separator between directories.

)* — Closes the non-capturing group and repeats zero or more times for intermediate directories.

[\w.-]* — Matches the final filename or directory name (zero or more characters, allowing the path to end at a directory with a trailing backslash).

$ — Anchors the match at the end of the string.

This pattern matches Windows paths like C:\Users\name\file.txt, D:\Projects, and E:\data.csv. It requires a drive letter prefix and uses backslashes as separators. The pattern does not support UNC paths (\server\share), paths with spaces, or long path syntax. For paths with spaces, add a space to the character classes.

Example Test Strings

InputExpected
C:\Users\name\file.txtMatch
\\server\share\pathNo Match
/usr/local/binNo Match
E:\data.csvMatch
C:\Program FilesNo Match

Try It — Interactive Tester

//
gimsuy
No matches found.
Pattern: 34 charsFlags: noneMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →