【问题标题】:Unify multiple Django url prefixes by pattern to same page按模式将多个 Django url 前缀统一到同一页面
【发布时间】:2020-11-01 15:41:53
【问题描述】:

我有以下 Django url 模式:

urlpatterns += patterns('some.utils',
    url(r'^media$', logic0),
    url(r'^tickets$', logic1),
    url(r'^dogs$', logic2),
    url(r'^some-location-with-ending.png$', LOGIC3),
    url(r'^some-location-other-ending.svgh$', LOGIC3),
    url(r'^some-location-number-123$', LOGIC3),
    url(r'^some-location-5$', LOGIC3),
)

有没有一种简单的方法(正则表达式?)将所有some-location 前缀统一在一行中?当然也适用于从some-location开始的未来模式

【问题讨论】:

    标签: django regex django-urls


    【解决方案1】:

    您可以交替列出它们|

    ^some-location-(?:with-ending\.png|other-ending\.svgh|number-123|5)$
    

    Regex demo

    一个不太具体的模式可以匹配 some-location- 并匹配以下单词字符,可选地重复它之前的 - 并可选地匹配扩展名。

    ^some-location-\w+(?:-\w+)*(?:\.\w+)?$
    

    Regex demo

    【讨论】:

    • 谢谢,你在 Django urls 中试过这个吗?对我来说它不起作用,也许我错过了其他东西......在some-location-之后的所有内容都没有更简单的正则表达式吗?例如。 ^some-location-.*
    • @MTZ4 我没有尝试过 Django url 中的模式。正则表达式演示中列出的当前网址是否也不起作用?您可以使用^some-location-.*,但这是一个非常广泛的模式,因为.* 将匹配除换行符以外的任何字符,并且它也将仅匹配some-location-
    • 是的,其他正则表达式也不能正常工作。我使用的 Django 1.6 可能是相关的。像url(r'^mypath/(?P<path>.+)', ..) 这样的正则表达式效果很好
    • 如果可行,也许它可能是这样的url(r'^mypath/(?P<path>some-location-.*)', ..)url(r'^(?P<path>some-location-.*)', ..)
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2020-11-22
    • 2013-02-20
    • 2023-02-02
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多