Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for Unix file path
Regex pattern · validation

Regex for Unix file path

Regex for Unix file path: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^\/(?:[^\/\x00]+\/?)*$/ as an Unix file path regex. It matches "/" and "/usr/local/bin", and rejects "relative/path" and "C:\Windows". A valid-looking path is not a safe one.

Last updated · Maintained by FreeAIToolz · How we test

/^\/(?:[^\/\x00]+\/?)*$/
  • /matches
  • /usr/local/binmatches
  • /home/user/file.txtmatches
  • /var/log/matches
  • relative/pathno match
  • C:\Windowsno match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^\/absolute paths start with /
(?:[^\/\x00]+\/?)*$segments of any characters except / and the null byte

Examples

InputResult
/✓ Matches
/usr/local/bin✓ Matches
/home/user/file.txt✓ Matches
/var/log/✓ Matches
relative/path✗ No match
C:\Windows✗ No match
(empty string)✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

A valid-looking path is not a safe one. Never pass user input straight to the file system; resolve and check it against an allowed base directory to prevent path traversal (../).

When to use this pattern

Config validation in DevOps tools and deployment scripts.

Use it in your language

JavaScript

const re = /^\/(?:[^\/\x00]+\/?)*$/;
re.test(input); // true or false

Python

import re
pattern = re.compile(r'^\/(?:[^\/\x00]+\/?)*$')
bool(pattern.search(value))

PHP

$ok = preg_match('~^\\/(?:[^\\/\\x00]+\\/?)*$~', $value) === 1;

Java

Pattern pattern = Pattern.compile("^\\/(?:[^\\/\\x00]+\\/?)*$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^\/(?:[^\/\x00]+\/?)*$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for Unix file path?
/^\/(?:[^\/\x00]+\/?)*$/. A valid-looking path is not a safe one. Never pass user input straight to the file system; resolve and check it against an allowed base directory to prevent path traversal (../).
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abc/xyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.