Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex django url中命名组的动态数目_Regex_Django_Url Pattern - Fatal编程技术网

Regex django url中命名组的动态数目

Regex django url中命名组的动态数目,regex,django,url-pattern,Regex,Django,Url Pattern,我想开发一个带有动态URL的web服务 带有命名组的通用url模式如下所示: (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive') (r'^(?P<cat1>)/(?P<cat2>)/$', 'module.views.function') (r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>

我想开发一个带有动态URL的web服务

带有命名组的通用url模式如下所示:

(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive')
(r'^(?P<cat1>)/(?P<cat2>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/(?P<cat4>)/$', 'module.views.function')
(r'^articles/(?P\d{4})/(?P\d{2})/$,'news.views.month_archive')
出于我的目的,我需要更具活力,因为我从一开始就不知道组的数量

例如,可能的URL可以是:

  • 文章/帖子/评论
  • 文章/文章/作者
  • 文章/职位/
我可以用这样的东西:

(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive')
(r'^(?P<cat1>)/(?P<cat2>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/(?P<cat4>)/$', 'module.views.function')
(r'^(?P)/(?P)/$,“module.views.function”)
(r’^(?P)/(?P)/(?P)/$,“模块.视图.函数”)
(r'^(?P)/(?P)/(?P)/(?P)/$”,“module.views.function”)
。。
等等有没有更聪明的方法?提前谢谢

等待如果您只有一篇文章,那么您希望它是
article/post/
,否则您希望它是
articles/post/

由于URL只是正则表达式,您可以执行以下操作

(r'^articles?/post/$', 'some_view')
测试
s
中的0或1

但从根本上说,你的URL似乎没有意义,当你写
文章/文章/评论时,听起来你想在所有的文章上发表评论?与
article/post/
相同,这是什么意思?你想发哪篇文章(你只有一篇,最多一篇)

通常URL看起来像
articles/5/post/comments
,这意味着“我想在pk为5的文章上发表评论”


如果我的回答没有帮助,我很抱歉。我想我没有真正理解你的问题。

这让我感兴趣,我以前一直想要它,但从来没有想出一个好的解决方案。对不起,我的示例URL有误导性。问题更一般,不是关于文章或帖子,而是关于如果斜杠(命名组)的数量事先未知,如何在斜杠之间提取信息。您是否尝试过
(r'(?P\w+)
(注意缺少的
^
$
)?但我不确定视图是否可以获取匹配的命名正则表达式组的列表。如果不起作用,请尝试
(r'^(?)$)
(匹配整个URL)并拆分
匹配
/