I have to match URLs in my Django re_path function.
The structures to be matched are as follows:
- Any URL must start with an optional
/userstring followed with a/profilepart - After that, there should be either
/, other URL subparts, or end of string
Here below the examples for allowed URLs:
- /profile
- /profile/
- /profile/asd
- /profile/asd/
- /user/profile
- /user/profile/
- /user/profile/asd
- /user/profile/asd/
- /user/profile/asd/blah
I tried the following, but it fails:
re_path(r'^profile/?.*$', views.my_view)
Any help is appreciated.
CodePudding user response:
You can use
^/(?:user/)?profile(?:/.*)?$
See regex demo. Details:
^- start of string/- a/char(?:user/)?- an optionaluser/stringprofile- a fixesd string(?:/.*)?- an optional sequence of a/char and then any zero or more chars other than line break chars as many as possible$- end of string.
