Reputation: 8897
I need do match path of my image:
images/05a813eb-df00-4ed6-b8a5-2930f03fbf5d.jpg
I split it by dir, name and ext
def url(self, name):
prefix, _ = name.split('/')
file_name, ext = _.split('.')
return reverse('image_storage',
args=[prefix, file_name, ext])
so I have images
, 05a813eb-df00-4ed6-b8a5-2930f03fbf5d
, jpg
my url pattern:
url(r'^img/(?P<prefix>\w+)/(?P<uuid4>[0-9a-f][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(?P<ext>\w+)
but it doesn't matches, help me find solution please.
Upvotes: 1
Views: 1134
Reputation: 626920
You can use
^images/(?:(?P<prefix>\w+)/)?(?P<uuid4>[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\.(?P<ext>\w+)
See the regex demo
The optional dir after images/
is matched with an optional group (?:(?P<prefix>\w+)/)?
. The ?
quantifier matches 1 or 0 occurrences. If there can be more than 1, use *
instead of ?
(but I guess you'd have to think of correct "prefix" group boundaries).
Also, [0-9a-f][0-9a-f]{8}
in your regex requies 9 chars, but there are 8 in fact.
3 consecutive -[0-9a-f]{4}
can be just shrunk into another non-capturing group (?:-[0-9a-f]{4}){3}
.
NOTE: It might be a good idea to prepend the pattern with (?i)
(case insensitive modifier): (?i)^images/(?:(?P<prefix>\w+)/)?(?P<uuid4>[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\.(?P<ext>\w+)
Upvotes: 2