C.W.K.
Stream
Lesson 09 of 12 · published

File Paths

~8 min · paths, files

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Unix and Windows live differently

Unix paths use /; Windows uses \ (with various escapes) AND / (modern Windows accepts both). Regex for both is awkward. Use your language's path library when you can.

Common patterns

Match a Unix-style path:

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

Match a filename with extension:

([\w-]+)\.(\w+)$

Match an extension only (after the last dot):

\.([^.]+)$

Match all paths in a string:

(?:\./|/|~/)[\w./-]+

Starts with ./, /, or ~/; followed by path-friendly characters.

Replace your manual splitting with the library

Python pathlib.Path gives you .name, .stem, .suffix, .parent, .parts — no regex needed.

Same in JS (path module), Go (path/filepath). Reach for the library for actual path manipulation. Regex is only for finding path-shaped substrings in larger text.

Code

Path patterns·python
import re
from pathlib import Path

# Find paths in text
PATH_FIND = re.compile(r'(?:\./|/|~/)[\w./-]+')
re.findall(PATH_FIND, 'edit /etc/hosts and ./local.cfg and ~/Documents/notes.md')
# ['/etc/hosts', './local.cfg', '~/Documents/notes.md']

# Extension extraction with regex
EXT = re.compile(r'\.([^.]+)$')
m = EXT.search('photo.tar.gz')
m.group(1)  # 'gz'  — only the LAST extension

# Better: use pathlib
p = Path('photo.tar.gz')
p.suffix    # '.gz'
p.suffixes  # ['.tar', '.gz']
p.stem      # 'photo.tar'
p.name      # 'photo.tar.gz'
p.parent    # PosixPath('.')

# Filename without extension
FNAME = re.compile(r'([\w-]+)\.(\w+)$')
m = FNAME.search('photo.jpg')
print(m.group(1), m.group(2))  # 'photo' 'jpg'

External links

Exercise

Write a script that reads a directory, prints all files matching a regex (e.g., starts with 'log', ends with '.txt'). Use pathlib.Path.iterdir for listing and a regex for the name filter.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.