Using Python Regular Expression in Django


I have an web address:

I want to be able to pass CompanyA to a view using regular expressions.

This is what I have:


and it doesn't match.

Ideally all URL's that look like would pass x to the view.

Thanks in advance!

10/25/2009 12:08:20 AM

Accepted Answer

You need to wrap the group name in parentheses. The syntax for named groups is (?P<name>regex), not ?P<name>regex. Also, if you don't want to require a trailing slash, you should make it optional.

It's easy to test regular expression matching with the Python interpreter, for example:

>>> import re
>>> re.match(r'^org/?P<company_name>\w+/$', 'org/companyA')
>>> re.match(r'^org/(?P<company_name>\w+)/?$', 'org/companyA')
<_sre.SRE_Match object at 0x10049c378>
>>> re.match(r'^org/(?P<company_name>\w+)/?$', 'org/companyA').groupdict()
{'company_name': 'companyA'}
10/25/2009 12:20:42 AM

Your regex isn't valid. It should probably look like


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow