Warm tip: This article is reproduced from serverfault.com, please click

RegEx for a url path that can just be a forward slash

发布于 2020-11-27 12:36:28

I am trying to created a regular expression to validate a Url path. I have come up with this:

^\/([a-zA-Z0-9\-]+)?$

Which allows me the have / or /moo or a more complex /products-123 but it doesn't allow me to use multiple forward slashes like /blog/posts-123. Can someone help me with this?

Ideally it should be able to allow:

  1. Just a forward slash for the home route
  2. A forward slash followed by alpha numeric (with dashes)
  3. Step 2 duplicated indefiniately
  4. It should not allow any path to end with a forward slash

If someone could help me with this, it would be great

Questioner
r3plica
Viewed
0
Peter Thoeny 2020-11-28 16:07:58

This regex allows

  • a single slash, or
  • a slash, followed by alphanumeric chars and dashes, repeated 1 or multiple times:

let urls = [
  '/',
  '/aaa-bbb',
  '/aaa-bbb/ccc',
  '/aaa-bbb/ccc/ddd',
  '/aaa-bbb/ccc/ddd/eee',
  '',  // empty
  '//double-slash',
  '/end-with-slash/',
];
let regex = /^(\/|(\/[a-zA-Z0-9\-]+)+)$/;
urls.forEach((url) => {
  let result = regex.test(url);
  console.log('"' + url + '"  ==> ' + result);
});

Result:

"/"  ==> true
"/aaa-bbb"  ==> true
"/aaa-bbb/ccc"  ==> true
"/aaa-bbb/ccc/ddd"  ==> true
"/aaa-bbb/ccc/ddd/eee"  ==> true
""  ==> false
"//double-slash"  ==> false
"/end-with-slash/"  ==> false

As you can see from the result, it guards against an empty url path, a url path with double slashes, and a url path ending in a slash.

Explanation of regex:

  • ^(\/|(...)+)$ - expect a single slash, or a 1+ sequence in parenthesis
  • \/[a-zA-Z0-9\-]+$ - sequence in parenthesis is a slash, followed by one or more chars of alphanumeric and dash