difference between '^$' and '' in urls django

99darshan picture 99darshan · Jun 25, 2015 · Viewed 15.2k times · Source

What is the difference between the below two url patterns in django?

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

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

To my understanding both '^$' and '' refer to a empty string. What does '^$' and '' specify actually?

Answer

Rahul Gupta picture Rahul Gupta · Jun 25, 2015

In regular expressions, ^ and $ are special characters.

^ (Caret):

^ matches the start of the string.

Lets say my regex was ^a, then the regex will look for a in the start of the string:

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

$ (Dollar sign):

$ matches the end of the string.

If my regex was b$, then it will match b at the end of the string:

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

Using r'^$':

Using both ^ and $ together as ^$ will match an empty line/string.

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

When Django encounters an empty string, it will go to the index page.

Using r'':

When you use r'', Django will look for an empty string anywhere in the URL, which is true for every URL.

So, if your urlpattern was like this:

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

All your urls will go to index page.