gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:18 25 4
gpt4 key购买 nike

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

关于python - Django 上的正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com