1

I'm trying to create regex to check against a valid directory prefix, where directory names must not be empty, and can contain any alphabet characters [a-zA-Z] and any numbers [0-9]. They can also contain dashes (-) and underscores (_) but no other special characters. A directory prefix can contain any number of forward slashes (/), and a valid path must not end with a forward slash (/) either.

Valid examples would be:

  • /abc/def
  • /hello_123/world-456
  • / (a special case where a single forward slash is allowed)

Invalid examples would be:

  • /abc/def/
  • /abc//def
  • //
  • abc/def
  • /abc/def/file.txt

So far I have ^(\/+(?!\/))[A-Za-z0-9\/\-_]+$ but it's not checking against what would be empty directory names (e.g. two forward slashed one after the other /abc//def), or path's ending with a slash (e.g. /hello_123/world-456/)

2
  • Tangentially, slash is not a regex metacharacter, and doesn't need backslash escaping in many regex dialects. In violation of the regex tag guidance, your question fails to reveal which regex tool you need help with. Commented Jul 9, 2022 at 19:06
  • /+ will match ALL slashes, so (?!\/) will always be true. Commented Jul 9, 2022 at 21:53

2 Answers 2

4

I propose ^((/[a-zA-Z0-9-_]+)+|/)$. Explanation:

  • ^ and $: Match the entire string/line
  • (/[a-zA-Z0-9-_]+)+: One or more directories, starting with slash, separated by slashes; each directory must consist of one or more characters of your charset
  • (...)+|/: Explicitly allow just a single slash

You might want to use noncapturing groups (?:...) here: ^(?:(?:/[a-zA-Z0-9-_]+)+|/)$. If you only use regex match "testing" this won't matter though.

Side note: Do you want to allow directory names to start with -, _ or a number? This is fairly unusual for names in most naming schemes. You might want to use [a-zA-Z][a-zA-Z0-9-_]* to require a leading letter.

Sign up to request clarification or add additional context in comments.

Comments

0

In case someone is looking for a function to check whether a value is a path or not, here it goes:

function isPath (value = "") {
  return value.toString()
    .replace(/\\/g, '/')
    .match(
      /^(\/?([a-zA-Z0-9-_,\.])+)+$/
    );
}

If you DO NOT want to accept files in your path, remove the \. in the end of the RX.

Also, if you want to check if something is a real url, the most straight forward to do to that is to use the native checker for you:

function isURL (value = "") {
  try {
    new URL(value);
    return true;
  } catch (error) {
    return false;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.