python - urls django 中 '^$' 和 '' 之间的区别

标签 python regex django django-urls

django 中以下两种 url 模式有什么区别?

url(r'^$', views.indexView, name='index'),

url(r'', include('registration.urls'))

据我了解,“^$”和“”均指空字符串。 '^$' 和 '' 实际上指定了什么?

最佳答案

在正则表达式中,^$是特殊字符。

^(插入符号):

^ 匹配字符串的开头。

假设我的正则表达式是 ^a,那么正则表达式将在字符串的开头查找 a:

'a'    # Matches 'a' in 'a'  
'abc'  # Matches 'a' in 'abc'
'def'  # Not match because 'a' was not at the beginning 

$(美元符号):

$ 匹配字符串的结尾。

如果我的正则表达式是 b$,那么它将匹配字符串末尾的 b:

'b'     # Matches 'b' in 'b'
'ab'    # Matches 'b' in 'ab'
'abc'   # Does not match 

使用r'^$':

同时使用 ^$ 作为 ^$匹配空行/字符串。

url(r'^$', views.indexView, name='index')

当Django遇到空字符串时,会跳转到index页面。

使用 r'':

当您使用 r'' 时,Django 将在 URL 中的任何位置查找空字符串,这对每个 URL 都是如此。

所以,如果您的 urlpattern 是这样的:

url(r'', views.indexView, name='index')

您所有的网址都将转到 index 页面。

关于python - urls django 中 '^$' 和 '' 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056789/

相关文章:

c# - 使用正则表达式和清理字符串内存?

python - Matplotlib Savefig 不会覆盖旧文件

python - python中与append()函数相反的是什么?

ruby - 计算两个字母一起出现的次数

python - 命名空间理解

python - 在 Django 中,如何在运行 syncdb 时从 SQL 文件创建表

mysql - 1045, "Access denied for user ' root' @'localhost'(使用密码 : NO)")

python - Django - 在上传图像时使用 instance.id

python - 迭代数据帧行

python - 用正则表达式抓取带有可选 <spans> 的 <p>