0

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_\/]+\/"

Do I need a lookahead?

Alex K
  • 129
  • 6
  • Windows allows Unicode paths. Don't force me to use A-Z only. It can also contain spaces. What kind of path should this be? Part of a URL or Linux Path? Linux Paths can even contain (escaped) slashes, IMHO. – Thomas Weller Jan 12 '22 at 10:19
  • Does this answer your question? [Check whether a path is valid in Python without creating a file at the path's target](https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta) – Thomas Weller Jan 12 '22 at 10:25

1 Answers1

2

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.
JvdV
  • 70,606
  • 8
  • 39
  • 70