[Answer]-Django: match one or more from a set of keyworded regular expressions in an urlconf

1👍

What you’re wanting is:

url(r'^base_url/(?P<serial>[^/]{13}/$', view_method),

with the addition of optional groups for the end and start kwargs, so:

# Optional, non-capturing group surrounding the named group for each (so you don't have to capture the slashes or the "e" or "s"
(?:e(?P<end>\d{8})/)

Then, allow up to 2 of those, in either order:

((?:s(?P<start>\d{8})/)|(?:e(?P<end>\d{8})/)){0,2}

The result is:

url(r'^base_url/((?:s(?P<start>\d{8})/)|(?:e(?P<end>\d{8})/)){0,2}(?P<serial>[^/]{13})/$', view_method),

Disclaimer, I wrote this in this box, so it’ll take me a moment to test it and update the answer (if it’s wrong).

Update:

Indeed, it worked 🙂 I matched the following:

http://127.0.0.1:8080/base_url/e77777777/s88888888/1234567890123/
http://127.0.0.1:8080/base_url/s88888888/e77777777/1234567890123/
http://127.0.0.1:8080/base_url/s88888888/1234567890123/
http://127.0.0.1:8080/base_url/e77777777/1234567890123/
http://127.0.0.1:8080/base_url/1234567890123/

The kwargs looked like this (raised in an exception from the get method of a sub-class of View when requested with all three segments – the end and/or start were None when left out):

{'start': u'88888888', 'serial': u'1234567890123', 'end': u'77777777'}

Leave a comment