2

In the following url:

(r'^videos/view/(?P<video_id>[^/]+)/$'
  • What does the r' mean/do?
  • What does the ?P mean/do?
  • How is the <video_id> escaped by the regex?

In other words, how is the above different than:

'^/videos/view/[^/]+/$'
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

5

r'' marks a raw string, so that you don't have to double-escape backslashes. In this case, it's not necessary because there aren't any, but a lot of people always do it for regexes anyway.

(?P<video_id>[^/]+) is a Python extension to regexes that "names" that capture group video_id. In Django, this means that the match is sent to the view as a keyword argument video_id; if you did view/([^/]+)/$, it would be sent as the first positional argument. In your example, though, there are no parens at all, meaning that the view wouldn't get any arguments!

Danica
  • 28,423
  • 6
  • 90
  • 122
  • Thanks, what does the actual `?P` mean, or is this the non-regex "python extension" that you mentioned? – David542 Apr 19 '12 at 06:13
  • 1
    The `?P` is just part of the syntax saying it's a named group. If you left it out, i.e. `([^/]+)`, it'd look for a literal `` in the string. More details [in the docs](http://docs.python.org/library/re.html) (search for "?P<", there's no direct link). – Danica Apr 19 '12 at 06:17
  • [what does “P” stand for?](http://stackoverflow.com/questions/10059673/named-regular-expression-group-pgroup-nameregexp-what-does-p-stand-for) – Nelloverflow Apr 19 '12 at 06:23