1
votes

I can't match an email address with a trailing slash in my url regex, and I can't figure out why. Here's the regex that matches the email address with no trailing slash:

r'^customer/(?P<customer_email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,63}$)$'

As expected, this matches /customer/[email protected], and not /customer/[email protected]/

I would have thought that appending /? would work, given that the regex to match the domain suffix of the email address should not greedily match the slash. (This was the solution to many of the other duplicate regex trailing-slash questions).

r'^customer/(?P<customer_email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,63}$)/?$'

As expected, this matches /customer/[email protected], but unexpectedly it doesn't match /customer/[email protected]/. Why?

APPEND_SLASH in settings.py is not set. I don't want to capture the slash as part of the customer_email url parameter.

1
With $, you require the end of string. Remove the first $. See regex101.com/r/wQ3x4N/1 - Wiktor Stribiżew
That did it thanks. I had the mistaken impression that it was also required for the end of url parameter capturing groups. If you post that as an answer I'll accept it. - Escher

1 Answers

2
votes

The $ anchor means the end of string, and the first time you have it inside a consuming pattern, it requires the end of string there.

Thus, you need to remove the first $ in your pattern and use

^customer/(?P<customer_email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,63})/?$

See the regex demo.