Reputation: 33
I'm trying to build a regex to validate directory path but I can't found a good way to do that. Could someone help me? examples :
/test/ -> could match
/test/toto/tata -> could match
\test\ -> could match
\test\toto\tata -> could match
//test/ -> could not match
\\test\ -> could not match
/test//toto -> could not match
/test\tata -> could not match
EDIT : i try this regex but it doesn't match all cases.
^(\/{0,1}(?!\/))[A-Za-z0-9\/\-_]+(\.([a-zA-Z]+))*$
Upvotes: 0
Views: 555
Reputation: 626690
It looks like you want to make sure there is at least one char in between the directory delimiters, the string can only start with a single directory delimiter and can optionally end with a directory delimiter.
As the string.Concat(System.IO.Path.GetInvalidPathChars())
(reference) returns "\"<>|\0\u0001\u0002\u0003\u0004\u0005\u0006\a\b\t\n\v\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"
, you can actually put the [^"<>|\u0000-\u001f]+
in the regex to match subfolder names and use
var pattern = @"^(?=([/\\]))(?:\1[^\\/""<>|\u0000-\u001f]+)+\1?$";
See the regex demo.
Details:
^
- start of string(?=([/\\]))
- next char must be a /
or \
directory separator char (captured into \1
)(?:\1[^\\/""<>|\u0000-\u001f]+)+
- one or more repetitions of a directory separator char followed with one or more occurrences of valid path and directory separator chars, i.e. any chars other than \
, /
, "
, <
, >
, |
and the control ASCII chars\1?
- an optional directory separator char captured into Group 1$
- end of string.Upvotes: 1