How does Django's `url` template tag reverse a Regex?
<p>How does Django's <code>url</code> template tag work?  What magic does it use under the covers to "reverse" a regex?</p>

<p>You give it a regex like this:</p>

<pre><code>urlpatterns = [
    # ex: /polls/5/
    url(r'^(?P&lt;question_id&gt;[0-9]+)/$', views.detail, name='detail'),
]
</code></pre>

<p>... and then in your template you can generate a URL that matches that pattern like this:</p>

<pre><code>&lt;a href="{% url 'detail' question.id %}"&gt;{{ question.question_text }}&lt;/a&gt;
</code></pre>

<p>How does that work?  Normally a regex is used to <strong>parse</strong> text, not <strong>generate</strong> it. Are there built-in tools in the <code>re</code> module that provide this functionality?</p>

<p>My question is not about how to use Django, or how to parse text with a Regex. Instead I'm interested in learning how I can use regular expressions in this "string template" way elsewhere.</p>

<p>The key to reversing the regex is the <a href="https://github.com/django/django/blob/master/django/utils/regex_helper.py#L50" rel="nofollow"><code>normalize()</code></a> function, which takes a regex and returns a list of possibilities. Each possibility is a tuple of a placeholder string and a list of parameters. </p>

<p>The <code>reverse()</code> function first checks if the parameters match the list of parameters for the placeholder. If it matches, the placeholder string is formatted with the arguments passed to <code>reverse()</code> (with a simple <code>'string' % parameters</code>). This string is then matched against the original regex. That's necessary because the parameters for the placeholder string don't have any restrictions, so checking against the original regex ensures that e.g. a group with <code>\d+</code> only contains numbers. </p>

<p>If a string formatted with the passed parameters matches the original regex, it's a valid url, and returned. </p>

python regex django