Home > Back-end >  Regex for folder path: only 1 subfolder
Regex for folder path: only 1 subfolder

Time:01-25

I would like to ask for help from people that have more advanced regex understanding than me. I have spent many hours trying stuff and also gone thru the tutorials on youtube and I'm at my wits end because it kind of works but the regex pattern is kind of broad I'm unable to narrow it down

Basically I'm using this regex

apidocs\/static\/[^\/] [.](?:png|jpg|jpeg|gif|pdf)

so it will consider this valid

./apidocs/static/mypicture.jpg

also this will be valid

apidocs/static/mypicture.jpg

regex demo:

https://regex101.com/r/p1EA9m/1

But I find that these are also valid which is not my intention

./traapidocs/static/mypicture.jpg

./whatever/apidocs/static/mypicture.jpg

How can i configure the regex so that only these 2 patterns are valid (root folders are ./apidocs or apidocs)


    ./apidocs/static/mypicture.jpg

    apidocs/static/mypicture.jpg

I'm using this in a python script btw, and found that putting a caret infront in a group does not work. Maybe there is a simpler way to form the regex.

Thank you in advance to anyone that is able to help!

CodePudding user response:

You can use

^(?:\.\/)?apidocs\/static\/[^\/] \.(?:png|jpe?g|gif|pdf)$ 

See the regex demo.

Details:

  • ^ - start of string
  • (?:\.\/)? - an optional ./ string
  • apidocs\/static\/ - a apidocs/static/ string
  • [^\/] - one or more chars other than /
  • \. - a dot
  • (?:png|jpe?g|gif|pdf) - png, jpg or jpeg, gif, pdf
  • $ - end of string

CodePudding user response:

This ones seems to work for your inputs:

^(\.\/)?apidocs\/static\/[^\/] [.](?:png|jpg|jpeg|gif|pdf)$

Demo: https://regex101.com/r/VA0bKz/1

  • Related