Gaurav Gaurav - 1 month ago 8
Python Question

Pass email as regex in django url

I am trying to pass email as parameter in django URL. I want to pass email as well as normal string and number also in URL as arguments.

url(r"search_connections/(?P<data>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$", "search_connections", name="search_connections"),


It's working properly for email as a parameter. But for normal string like "abc" it's not working:

working for "/search_connections/abc@test.com/"
not working for "/search_connections/abc/"


I want this URL to work for both.

Answer

You may try simply use | (or) with \w+:

r'search_connections/(?P<data>\w+|[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$'

However I think regex for email just isn't a robust solution to match all valid emails.