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?
CodePudding user response:
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.