سؤال

I'm using Django and would like to match the URLs domain.com/w and domain.com/words. I have a configuration line of the form:

url(r'^w(ords)?$', 'app_name.views.view_words')

view_words takes only one parameter (request), but it seems that Django captures the (ords) part of the regular expression and passes it to the view. When I remove (ords) from the regex and access domain.com/w, it works properly.

The Django documentation and similar StackOverflow questions cover how to capture optional URL parameters, but I do not want to capture any parameters from the URL. Is there a way to match an optional element of a URL without capturing it as a parameter?

هل كانت مفيدة؟

المحلول

Yes, using a non-grouping parenthesis, (?:...), so something like this:

url(r'^w(?:ords)?$', 'app_name.views.view_words')

See also the documentation of python regular expressions

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top