PatternRegex

Match a Unix file path

Match an absolute Unix or Linux file path — one or more slash-separated segments of word characters, dots and dashes, starting from the root.

Last updated

Pattern
^(?:/[\w.-]+)+/?$
Open in Regex Tester & Builder

Matches

  • /usr/local/bin
  • /home/ada/.bashrc
  • /var/log/app.log

Doesn’t match

  • relative/path/here
  • /has a space/in it

Why it’s written this way

(?:/[\w.-]+)+ requires one or more repetitions of a leading slash followed by a segment of word characters, dots or dashes — word characters here cover letters, digits and underscore, so ordinary filenames, dotfiles like .bashrc, and dashed names like app-config.json all fit one segment. Anchoring with ^ and $ (plus an optional trailing slash) means the whole string has to be the path, not just contain one.

Requiring the leading slash on every segment is what makes this specifically an absolute-path matcher — a relative path with no leading slash never gets past the very first repetition.

Edge cases to know

  • Spaces in a path fail by design, even though many real Unix filesystems allow them — \w does not include space, so a path like /home/ada/my file.txt only matches up to 'my'. Escape or quote such paths before feeding them to a shell anyway.
  • It has no concept of '.' or '..' as special segments, so /home/../etc matches the same as any other path even though it means something different to the filesystem.
  • Filenames using characters outside [\w.-] — spaces aside, things like @, +, or non-ASCII letters, all valid on most Unix filesystems — will break the match partway through.

Related in Patterns