Skip to main content
 首页 » 编程设计

python之Django 上的正则表达式不起作用

2024年08月20日30thcjp

我对 Django 比较陌生,所以我正在做 this tutorial ,但我遇到了正则表达式的问题:

对于这个 View

def viewArticle(request, month, year): 
     text = "Displaying articles of : %s/%s"%(year, month) 
     return HttpResponse(text) 

我应该创建一个这样的 url

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')