Nalyd
Nalyd

Reputation: 115

Regex for valid directory path

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:

Invalid examples would be:

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/)

Upvotes: 1

Views: 5527

Answers (2)

Felipe N Moura
Felipe N Moura

Reputation: 1617

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;
  }
}

Upvotes: 0

Luatic
Luatic

Reputation: 11171

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.

Upvotes: 4

Related Questions