Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex syntax

Tags:

python

regex

I am a beginner in python regex. so can someone help me understand following syntax?

r'^(?P<pk>\d+)/results/$'

I came across that statement while learning Django.


1 Answers

The expression broken down:

  • ^: match at the start of the string
  • (?P<pk>\d+): Match 1 or more digits (0-9) and capture that as the named group pk
  • /results/: Match the literal text /results/
  • $: Match at the end of the string.

So a URL path that starts with digits, followed by the text /results/ matches:

1234/results/
42/results/
3/results/

but anything else does not.

If used in a Django url configuration, the digits are captured and passed into the attached view as the pk keyword parameter.

like image 88
Martijn Pieters Avatar answered Dec 08 '25 20:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!