Non-capturing optional URL elements in Django

非 Y 不嫁゛ 提交于 2021-02-19 05:34:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!