嗨,我总是对正则表达式感到困惑,而且我不明白对其他帮助线程的响应。
基本上我的问题是,我可以合并
r'^input/?$'
和
r'^input/index.html?$'
进入这个?
r'^input(/(index.html?)?)?$'
在 Django 中,我收到此错误:
input() takes exactly 1 argument (3 given)
它仅在正确匹配时给出错误,所以也许这不是正则表达式问题?
最佳答案
就我个人而言,我不希望将这两个正则表达式结合起来。我认为有两种 url 模式,
url(r'^input/?$', input, name="input"),
url(r'^input/index.html?$', input),
比一个更具可读性。
但是,如果您确实想将两者结合起来,则可以使用非捕获括号:
r'^input(?:/(?:index.html?)?)?$'
一个简单的例子可能有助于解释:
>>> import re
>>> # first try the regex with capturing parentheses
>>> capturing=r'^input(/(index.html?)?)?$'
>>> # Django passes the two matching strings to the input view, causing the type error
>>> print re.match(capturing, "input/index.html").groups()
('/index.html', 'index.html')
>>> # repeat with non capturing parentheses
>>> non_capturing=r'^input(?:/(?:index.html?)?)?$'
>>> print re.match(non_capturing, "input/index.html").groups()
()
请参阅Regular Expression Advanced Syntax Reference页面了解更多信息。
关于python - Django URL 正则表达式出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10826342/