Reputation: 1916
private static readonly Regex FileDirectoryRegex = new Regex(@"^[^""\\:|<>*?]*\/{0,1}$");
if (folderName.EndsWith("/") || folderName.Contains("//"))
{
throw new ArgumentException());
}
How to add last if
statement validation to my FileDirectoryRegex
?
Upvotes: 1
Views: 90
Reputation: 626802
You can merge the if
conditions to your regex as follows:
@"^(?!.*//)[^""\\:|<>*?]*(?<!/)$"
^^^^^^^^ ^^^^^^
See the regex demo at RegexStorm (a little modified there since it is a multiline string demo)
The (?!.*//)
is a negative lookahead that will fail the match if the engine finds //
somewhere after 0+ chars other than a newline (.*
) and (?<!/)
is a negative lookbehind that will fail the match if there is a /
right before the end of string.
HOWEVER, lots of users say it is bad practice to cram all conditions into 1 regex, please consider choosing the more readable approach (the one you have now, split the conditions).
Upvotes: 4