[Answered ]-Most common regex on Django URLs

2đź‘Ť

There is not a “common” list that I use, but there are are a few common patterns, as well as some simple rules:

  1. The caret character (^) means “starts with”.
  2. The dollar sign ($) means “ends”.
  3. Question mark (?) means “optional”.
  4. You can group and named a pattern using the (?Ppattern) format.

So, for simple URLs, without any parameters, you’ll want to to learn the ^url$ pattern. Examples:

url(r'^foo$', 'app.view')
url(r'^foo/subdirectory/?$', 'app.view')

For parameters, you’ll want to use the grouping mechanism:

url(r'^foo/(?P<parameter_name>[-\w]+)/$', 'app.view')
url(r'^foo/(?P<parameter_name>[-\w]+)/(?P<parameter_two_name>[-\w]+)/$', 'app.view')

The [-\w] pattern means “Anything that isn’t whitespace”. The brackets [] establish that you’ll accept a character in a range of possible characters as a match, the \w is a short cut for “whitespace character”, and the - in front of the short cut means “anything not”. The “+” after the brackets means “the pattern before must repeat”.

RegEx’s are a full and complex topic on their own, but the above three examples cover about 90% of what’s in most of my urls.py files.

👤Jack Shedd

Leave a comment