[Answered ]-Regex interpretaion in Django tutorial

2👍

The (?P<question_id>.*) Says everything captured by the regex inside the parenthesis will be in a named group called question_id. It can be directly addressed. So the regex doesn’t know it is a foreign key or anything of the sort, just that there is a group named question_id. The parenthesis isn’t really matched in the incoming string.

The [0-9]+ matches and numeric string 1 or more digits long.

^ is the start of the string. $ is the end of the string. ^, $, (?P<question_id>, and ) are somewhat meta and aren’t impacted by the string so much as the string’s position and how the regex extracted groups will be referenced.

The captured group is passed to the view (detail in this case) as a keyword argument and it’s up to the view to make use of it in a meaningful way.

👤nephlm

0👍

The (?P<name>...) means that this regex has a named capture group, unlike the (...) syntax, which is a numbered capture group. Django takes the named parameters and passes them to your view.

0👍

^(?P<question_id>[0-9]+)/$

^ assert position at start of the string
(?P<question_id>[0-9]+) Named capturing group "question_id"
    [0-9]+ match a single character present in the list below:

        Quantifier: + Between one and unlimited times, as many times as possible, 
        giving back as needed [greedy]
        0-9 a single character in the range between 0 and 9

$ assert position at end of the string

Demo and full explanation: https://regex101.com/r/zV3rZ1/1

👤l'L'l

0👍

It captures [0-9]+ under the name question_id. Then it passes the captured number to the view function as a parameter. You can try it with re functions. It is not Django specific.

>>> import re
>>> re.match(r'^(?P<question_id>[0-9]+)/$', '122/').groupdict()
{'question_id': '122'}

Leave a comment