Unix Path Validation Regular Expression
Unix and Linux file system paths follow a hierarchical structure starting from the root directory (/). Paths can be absolute (starting with /) or relative (starting with ./ or ../). This regex validates common Unix path formats used in Linux, macOS, and other Unix-like operating systems, following the POSIX pathname specification. For Windows paths, see the Windows path validation article.
Recommended Solution
Explanation
^(\/[^\/ ]*)+\/?$- Absolute paths:\/- Starts with a forward slash.[^\/ ]*- Directory/file name (any characters except / and space).+- One or more path segments.\/?- Optional trailing slash.
^\.(\/[^\/ ]*)+\/?$- Relative paths starting with ./^\.\.\/([^\/ ]*\/)*[^\/ ]*$- Relative paths starting with ../ (parent directory).
Notes
- This regex validates the format of Unix paths but does NOT verify if the path exists on the filesystem.
- This pattern does NOT allow spaces in path names. Modify
[^\\/ ]*to[^\\/]*to allow spaces if needed. - Hidden files and directories (those starting with a dot) are supported (e.g., /home/user/.config).
- Special characters like *, ?, and [] which have meaning in shell globbing are allowed in this pattern but may need escaping in actual use.
- The pattern accepts both files and directories. Trailing slashes typically indicate directories but are not required.
- Symbolic links are validated by format but not resolved or distinguished from regular files/directories.
- For more robust path validation, consider using filesystem APIs in your programming language.
Implementation
Test Cases
| Path | Type | Valid |
|---|---|---|
| / | Root directory | |
| /home/user | Absolute path | |
| /usr/local/bin | Absolute path | |
| /var/log/system.log | Absolute file path | |
| ./relative/path | Relative path | |
| ./file.txt | Relative file | |
| ../parent/directory | Parent directory | |
| /path/to/directory/ | Trailing slash | |
| /path-with-dashes/file_name.ext | Dashes and underscores | |
| /path/with.dots/file.tar.gz | Multiple dots | |
| relative/path | Invalid relative (no ./) | |
| C:/Windows/System32 | Windows path | |
| /path with spaces/file | Contains spaces | |
| (empty string) | Empty string | |
| //double/slash | Double slash | |
| /path//file | Double slash in middle |