I'm relatively new to Django so I am doing this tutorial, but I encountered a problem with regular expressions:
我是Django的新手,所以我正在学习本教程,但是我遇到了正则表达式的问题:
For this view
对于这个观点
def viewArticle(request, month, year):
text = "Displaying articles of : %s/%s"%(year, month)
return HttpResponse(text)
I am supposed to create a url like that
我应该创建一个这样的url
url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name='articles')
and it works perfectly, for example when I enter http://.../articles/12/2014 I get "Displaying articles of: 12 / 2014", as I should.
它工作得很好,例如当我输入http://..。/article /12/2014我得到了“display articles: 12/2014”。
However, later (on page 27 of the PDF) I am advised to change the url to this:
然而,稍后(在PDF的第27页),我被建议将网址改为:
url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name='articles'),
and now it doesn't work anymore. Why could that be and how can I change my code? Thanks for any suggestions!
现在它不再工作了。为什么会这样,我该如何改变我的代码呢?谢谢你的任何建议!
1 个解决方案
#1
3
The tutorial says that you may use named capturing groups here:
教程说,您可以在这里使用命名捕获组:
(?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 <名称> …)类似于常规的圆括号,但是组匹配的子字符串可以通过符号组名进行访问。组名必须是有效的Python标识符,每个组名必须在正则表达式中定义一次。符号组也是一个编号的组,就像没有命名组一样。
The correct declaration of a named capturing group is (?P<name>...)
:
命名捕获组的正确声明为(?P
url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})', 'viewArticles', name='articles')
#1
3
The tutorial says that you may use named capturing groups here:
教程说,您可以在这里使用命名捕获组:
(?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 <名称> …)类似于常规的圆括号,但是组匹配的子字符串可以通过符号组名进行访问。组名必须是有效的Python标识符,每个组名必须在正则表达式中定义一次。符号组也是一个编号的组,就像没有命名组一样。
The correct declaration of a named capturing group is (?P<name>...)
:
命名捕获组的正确声明为(?P
url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})', 'viewArticles', name='articles')