Split URL with regex

Question:

I’m trying to get two inputs from a URL into a view by using regular expressions.

My urls.py line looks like this:

(r'^blog/(?P<match>.+)/', 'blog.views.blog'),

And this is my view:

def blog(request, match):
    pieces = match.split('/')

However, if my URL is "root.com/blog/user/3" pieces only returns [user].

In order for pieces to return [user],[3]`, a trailing slash has to be added to my URL: "root.com/blog/user/3/".

And as far as I know and according to my Python shell, the first URL should have returned [user],[3].

Am I missing something? Or does Django actually split strings differently from Python?

Asked By: bcoop713

||

Answers:

The problem is that your regexp doesn’t match the whole URL because the pattern ends with a slash, and your URL doesn’t.

But since regexp without an explicit $ at the end matches a prefix of a string, if you’ll have a look at your match variable you’ll notice that it is user/, not user/3 as you might expect.

Update: (more verbose explanation)

r'^blog/.*/' matches [blog/user/] and [blog/user/]3 (square brackets used to denote actually matched parts).

If you try r'^blog/.*/$' you’ll notice that blog/user/3 won’t match at all since there is not slash at the end.

Answered By: kirelagin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.