Python (re)

URL Path Segment in PY

Match individual `/segment` parts of a URL path, capturing each one.

Try it in the PY tester →

Pattern

regexPY
\/([^\/?#\s]+)   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"\/([^\/?#\s]+)")
input_text = "/users/42/posts?page=2"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

\/ matches the literal slash. ([^\/?#\s]+) captures one or more characters that aren't a slash, question mark, hash, or whitespace — i.e. one path segment. Useful for breaking apart a URL into its component pieces.

Examples

Input

/users/42/posts?page=2

Matches

  • /users
  • /42
  • /posts

Input

/api/v1/health

Matches

  • /api
  • /v1
  • /health

Input

no/path

No match

Same pattern, other engines

← Back to URL Path Segment overview (all engines)