Regex to Match Unix File Paths

Validate Unix/Linux file paths with this regex. Matches absolute paths like /usr/local/bin or /home/user/file.txt. Free regex tool.

Regular Expression

/^(?:\/[\w.-]+)+\/?$/

Token Breakdown

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

Detailed Explanation

This regex validates absolute Unix/Linux file paths. Here is the token-by-token breakdown:

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

(?: — Opens a non-capturing group for each path segment.

/ — Matches a literal forward slash, the Unix path separator.

[\w.-]+ — A character class matching one or more valid path segment characters. \w matches word characters (letters, digits, underscore), and we also allow dots (for file extensions and hidden files like .bashrc) and hyphens (common in directory and file names). The + requires at least one character per segment, preventing consecutive slashes.

)+ — Closes the non-capturing group and repeats it one or more times. This matches one or more path segments, each starting with a slash.

/? — Matches an optional trailing forward slash. Unix paths can optionally end with a slash to indicate a directory.

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

This pattern matches paths like /usr/local/bin, /home/user/file.txt, /var/log/, and /etc/nginx/nginx.conf. It requires an absolute path starting with / and does not match relative paths like ./config or ../parent.

The pattern does not allow spaces in path names. If you need to support spaces, add a space to the character class: [\w. -]+. It also does not match the root path / by itself, since the group requires at least one character after each slash. For a more permissive pattern, you could add the root as an alternative.

Example Test Strings

InputExpected
/usr/local/binMatch
/home/user/file.txtMatch
relative/pathNo Match
/var/log/Match
C:\Windows\System32No Match

Try It — Interactive Tester

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

Ctrl+Shift+C to copy regex

Customize this pattern →