Sreekanth Reddy Balne
Sreekanth Reddy Balne

Reputation: 3424

django url regex to match optional parameters

I need a regex that should match the following strings:

where, pk=24, username=sam, tab=tab_name

So far I have a url as:

url(r'^users/(?P<pk>\d+)/(?P<username>[-\w\d]+)?/?(?P<tab>[-\w\d]+)?/?', vw.ProfileView.as_view(), name='profile')

The above url matches everything above. But while using

{% url 'profile' pk=24 username="sam" tab="tab_name" %}

the output is : users/samtab_name

I know the problem here i.e, /? optional slash. But I don't want it to be optional when using {% url 'profile' pk=24 username="sam" tab="tab_name" %}

Help me with this.

Upvotes: 1

Views: 1016

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You may make your / obligatory by placing them together with the named capturing groups inside optional non-capturing groups:

^users/(?P<pk>\d+)(?:/(?P<username>[-\w]+))?(?:/(?P<tab>[-\w]+))?/?

See the regex demo.

Note that \w already matches digits, so you do not need \d inside the character classes.

Details

  • ^ - start of string
  • users/ - a literal substring
  • (?P<pk>\d+) - a named capturing group "pk" matching 1+ digtis
  • (?:/(?P<username>[-\w]+))? - an optional non-capturing group (there is ? quantifier after the closing )) matching
    • / - a / char
    • (?P<username>[-\w]+) - Group "username": 1+ word or - chars
  • (?:/(?P<tab>[-\w]+))? - an optional non-capturing group matching
    • / - a / char
    • (?P<tab>[-\w]+) - Group "tab": 1+ word or - chars
  • /? - an optional / char.

Upvotes: 3

Related Questions