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

Time:01-08

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 an optional /user string followed with a /profile part
  2. 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 optional user/ string
  • profile - 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.
  •  Tags:  
  • Related