【问题标题】:re_path unresolved regex (\d[1,2])re_path 未解析的正则表达式 (\d[1,2])
【发布时间】:2020-09-13 09:43:54
【问题描述】:
请告诉我为什么我的正则表达式无法解析,我只是从一本 Django 书籍中复制并粘贴,并尝试传递参数re_path(r'^time/plus/(\d[1,2])/$', hours_ahead)。刚刚尝试将参数额外的小时数传递给当前时间。
http://127.0.0.1:8000/time/plus/2
然后我收到找不到页面 (404) 错误。当前路径 time/plus/2 与其中任何一个都不匹配。
我不明白这里有什么问题。请帮忙,谢谢。
【问题讨论】:
标签:
python
django
path
python-re
【解决方案1】:
这是因为如果你只需要一个和两个这样的数字,这是错误的正则表达式,所以没有必要这样指定
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}/$'
【解决方案2】:
您的正则表达式存在一些问题:
^time/plus/(\d[1,2])/$
^ ^
- 要匹配一位或两位数字,您需要使用语法
\d{1,2}。 \d[1,2] 将匹配任何数字,后跟 1、逗号或 2。
- 您的正则表达式需要一个尾随斜杠,而您的输入似乎没有。
类似
^time/plus/(\d{1,2})/?$
可能会起作用。