Skip to the workspace
Pebellslearn by building
The Request–Response Flow  ›  Lesson

Regex Paths with re_path()

Regex Paths 14 minre_path() matches a URL against a regular expression instead of a route string, and named groups in the pattern are passed to the view as string keyword arguments.

django / Regex Paths with re_path()

Explore each scene at your own pace.

01 · The rule

The rule

Regex Paths with re_path()

Converters cover most URLs. Now the cookbook wants a monthly archive: /recipes/archive/2025/09/. The year must be exactly four digits and the month exactly two. int would happily accept 7 or 123456. When you need a rule that precise, you can describe the URL with a regular expression.

The rule

re_path() matches a regex; named groups arrive as strings.

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r"^archive/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$", views.archive),
]

def archive(request, year, month):
    # /recipes/archive/2025/09/  →  year="2025", month="09"
    ...

Read the pattern piece by piece:

  • r"..." is a raw string, so backslashes such as \d reach the regex engine untouched.
  • ^ anchors the start of the remaining path, $ anchors the end. Without $, archive/2025/09/anything would match too.
  • [0-9]{4} means exactly four digits.
  • (?P<year>...) is a named group: whatever it matches is passed as the keyword argument year.

The key difference from path(): no converters. Every captured value is a str, so the view converts with int(year) when it needs a number.

Two more rules. Use named groups rather than bare ( ) groups, so arguments arrive by name and cannot get swapped. And do not mix the two styles in one pattern; if any group is named, unnamed ones are ignored.

path() and re_path() can sit in the same urlpatterns list, and the usual first-match-wins order applies to both.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.