10

I have an web address:

http://www.example.com/org/companyA

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

This is what I have:

(r'^org/?P<company_name>\w+/$',"orgman.views.orgman")

and it doesn't match.

Ideally all URL's that look like example.com/org/X would pass x to the view.

Thanks in advance!

3 Answers 3

20

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'}
Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome. I was looking for something like this online!
2

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

r'^org/(?P<company_name>\w+)/$'

Comments

1

It should look more like r'^org/(?P<company_name>\w+)'

>>> r = re.compile(r'^org/(?P<company_name>\w+)')
>>> r.match('org/companyA').groups()
('companyA',)

Comments

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.