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 to validate relative path with single / or ending with /

I’m trying to compose a regex which checks the validity of a relative path. It should start with a / and if it has anything following it, it must also end with another /.

Examples:

  • / => valid
  • // => not valid
  • /abc => not valid
  • /abc/ => valid

I’m using the following at the moment which responds correctly for all cases except the single /: "^\/[ A-Za-z0-9_\/]+\/"

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

Do I need a lookahead?

>Solution :

I believe the following would work:

^\/(?:[^/\n]+\/)*$

See the online demo. You could match whichever characters you’d want to allow for inside the character class, but the above would mean:

  • ^\/ – Start-line anchor and a escaped forward slash;
  • (?:[^/\n]+\/)* – A non-capturing, 1+ negated characters ‘/’ or a newline, followed by an escaped forward slash, matched 0+ times;
  • $ – End-line anchor.
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