简体   繁体   English

Django URL正则表达式“不是有效的正则表达式”错误

[英]Django URL regex “is not a valid regular expression” error

I'm having a bit of trouble configuring the following url. 我在配置以下网址时遇到了一些麻烦。 I want it to be able to match a pages which start off with a category and then finish with a slug, examples: 我希望它能够匹配以一个类别开头,然后以一个小段结尾的页面,例如:

/category1/post1/
/category2/post2/
/category3/post3/
/category1/post4/
/category2/post5/

I've tried many different methods with no success... I always get an "is not a valid regular expression" error. 我尝试了许多不同的方法,但均未成功...我总是收到“不是有效的正则表达式”错误。 This is how I thought it should work: 这就是我认为应该起作用的方式:

url(r'^(?P<category1|category2|category3>[\w\-]+)/(?P<slug>[\w\-]+)/$', blog_post, name = 'blog_post'),

I am fairly new to regex and trying to learn so any help on this one with an explanation would be much appreciated :) 我是正则表达式的新手,尝试学习,因此对此解释的任何帮助将不胜感激:)

Your pattern is incorrect; 您的模式不正确; you are putting the alternative values in the wrong place. 您将替代值放在错误的位置。 You put them in the name of the group: 您将它们放在组的名称中:

(?P<category1|category2|category3>...)

Put them in the part the name is supposed to match instead: 将它们放在应该匹配名称的部分中:

(?P<category>category1|category2|category3)

Making the full registration: 进行完整注册:

url(r'^(?P<category>category1|category2|category3)/(?P<slug>[\w\-]+)/$', blog_post, name='blog_post'),

I'm assuming your blog_post callable looks something like: 我假设您的blog_post可调用看起来像:

def blog_post(category, slug):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM