1

I have the following url

url(r'^(?P<name>[A-Za-z0-9-]+)/$', 'user', name='user')

This matches URLS like /tom/ and /tom-max/ but not on URL's like /tom-2/ or tom-brandy-monster which I want.

Basically I would like to capture a combination of hyphens, letters and numbers.

UPDATE

This is in my urls.py

urlpatterns = patterns('',
    url(r'^$', 'homepage.views.home', name='home'),
    url(r'^user/', include('users.urls')),
    url(r'^plans/', include('plans.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

This is in my users/urls.py

urlpatterns = patterns(
    'users.views',
    url(r'^(?P<user>[A-Za-z0-9-]+)/$', 'user', name='user'), 
)

UPDATE2

The fault was in my views. This regex works for all the above-mentioned examples.

5
  • That looks like it should work. I suggest looking closely at patterns that occur before this one to see if they are snagging the request before it gets to this pattern. Commented Jul 13, 2011 at 4:55
  • @Peter: you are correct; see my answer. Commented Jul 13, 2011 at 4:56
  • That is users.urls.py? I hope you mean users/urls.py? Commented Jul 13, 2011 at 5:15
  • I'm not sure quite what's wrong. I presume in your testing you are prefixing them all with user/. And I presume that the only thing that you've left out of your urls.py files as they are put here are the imports? Commented Jul 13, 2011 at 5:30
  • 1
    Why do you believe that it doesn't match those? Commented Jul 13, 2011 at 5:36

1 Answer 1

4

What you have there will match all of these that you have specified (see below). You should check to make sure that (a) you don't have a URL pattern which will match earlier and (b) that this one is being included (one common culprit is using urlpatterns = ... rather than urlpatterns += ... after initialising it).

>>> import re
>>> urlpattern = re.compile(r'^(?P<name>[A-Za-z0-9-]+)/$')
>>> urlpattern.match('tom/').group('name')
'tom'
>>> urlpattern.match('tom-max/').group('name')
'tom-max'
>>> urlpattern.match('tom-2/').group('name')
'tom-2'
>>> urlpattern.match('tom-brandy-monster/').group('name')
'tom-brandy-monster'
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Chris Morgan, could yo have a look at my URLS to see what could be wrong? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.