3

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 because, well, anyone who can make sense of any but the most trivial regex gets a +1 by default.
thanx dude . i really needed the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.