首页 > 解决方案 > re_path 未解析的正则表达式 (\d[1,2])

问题描述

请让我知道为什么我的正则表达式无法解析,我只是从一本 Django 书籍中复制并粘贴,并尝试传递参数re_path(r'^time/plus/(\d[1,2])/$', hours_ahead)。只是试图将参数额外的时间传递给当前时间。

http://127.0.0.1:8000/time/plus/2

然后我得到了找不到页面(404)错误。当前路径 time/plus/2 与其中任何一个都不匹配。

我不明白这里有什么问题。请帮忙,谢谢。

标签: pythondjangopathre

解决方案


这是因为如果你只需要一个和两个这样的数字,这是错误的正则表达式,所以没有必要像这样指定

case 1:
only 1 and 2 is accept
want:time/plus/2/ --pass
want:time/plus/1/ --pass
want:time/plus/3/ --fail
regex: r'^time/plus/[1,2]/$'

case 2:
length of that is 1 or 2 
want:time/plus/2/ --single digit -pass
want:time/plus/33/ --two digit -pass
want:time/plas/333/ --three digit -fail 
regex: r'^time/plus/\d{1,2}/$'

推荐阅读