Python regular expression syntax … here is a solution to the problem.
Python regular expression syntax
I’m a beginner in python regular expressions. So can someone help me understand the following syntax?
r'^(? P<pk>\d+)/results/$'
I came across this statement while learning Django.
Solution
Expression decomposition:
-
^
: matches the beginning of the string -
(? P<pk>\d+):
Matches 1 or more numbers (0-9) and captures them as a named groupPK
-
/results
/ : matches the text /results/
-
$
: matches at the end of the string.
So a URL path that starts with a number followed by the text /results/
match:
1234/results/
42/results/
3/results/
But nothing else.
If used in a Django url configuration, the number is captured and passed as pk
to the keyword parameter in the attached View.