简体   繁体   中英

Python RegEx: How to conditionally match multiple optional ending characters in a URL

I have to match URLs in my Django re_path function.

The structures to be matched are as follows:

  1. Any URL must start with either /profile or /user/profile
  2. Any URL must end with either profile , or profile/ or profile/blabla

Here below the examples for allowed URLs:

  • /profile
  • /profile/
  • /profile/asd
  • /profile/asd/
  • /user/profile
  • /user/profile/
  • /user/profile/asd
  • /user/profile/asd/

I tried the following, but it fails:

re_path(r'^profile/?.*$', views.my_view)

Any help is appreciated, thanks!

You can use

^/(?:user/)?profile(?:/(?:[^/]+/?)?)?$

See regex demo . Details :

  • ^ - start of string
  • / - a / char
  • (?:user/)? - an optional user/ string
  • profile - a fixed string
  • (?:/(?:[^/]+/?)?)? - an optional sequence of
    • / - a / char
    • (?:[^/]+/?)? - an optional sequence of any one or more chars other than / and then an optional / char
  • $ - end of string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM