Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for folder path: only 1 subfolder

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

./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!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading