我对 Django 比较陌生,所以我正在做 this tutorial ,但是我遇到了正则表达式的问题:
对于此 View
def viewArticle(request, month, year):
text = "Displaying articles of : %s/%s"%(year, month)
return HttpResponse(text)
我应该创建一个像这样的网址
url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name='articles')
它工作得很好,例如当我输入 http://.../articles/12/2014 时我得到“正在显示文章:2014 年 12 月”,正如我应该的那样。
但是,稍后(在 PDF 的第 27 页上)建议我将 url 更改为:
url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name='articles'),
现在它不再起作用了。为什么会这样?我该如何更改我的代码?感谢您的任何建议!
最佳答案
教程说您可以使用 named capturing groups这里:
(?P<name>...)
Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.
命名捕获组的正确声明是 (?P<name>...)
:
url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})', 'viewArticles', name='articles')
关于python - Django 上的正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757159/