regex

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


Solution

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

    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.