Regex for valid directory path

Viewed 43

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

1 Answers

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.

Related