re_path() and Regular Expressions
Use re_path() when you need full regular-expression routing.
Syntax
re_path(r"^pattern$", view)When simple converters are not enough, re_path() lets you match URLs with a regular expression. Named groups (?P<name>...) become keyword arguments for the view.
Prefer path() for readability; reach for re_path() only for patterns it cannot express.
Example
from django.urls import re_path
from . import views
urlpatterns = [
# Match a 4-digit year archive: /archive/2026/
re_path(r"^archive/(?P<year>[0-9]{4})/$", views.archive),
]When to use it
- A developer uses re_path to match legacy URLs with optional trailing slashes during a site migration.
- A developer captures a year/month/day date from a URL using a regular expression pattern.
- A team uses re_path to match a URL segment that must be exactly four digits, like a year.
More examples
Match a four-digit year
Uses a named regex group to capture a four-digit year and pass it to the view.
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r"^articles/(?P<year>[0-9]{4})/$", views.year_archive),
]Date archive URL pattern
Matches a year and month in the URL using two named regex groups.
urlpatterns = [
re_path(
r"^archive/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$",
views.month_archive,
name="month-archive",
),
]Optional trailing slash
Uses a ? quantifier to make the trailing slash optional for backward-compatible legacy URLs.
urlpatterns = [
re_path(r"^legacy-page/?$", views.legacy_page, name="legacy"),
]
Discussion