问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/20734358/non-capturing-optional-url-elements-in-django