I am having trouble creating a regular expression to disallow the following four characters and limit the size:
/
#
?
\
What I currently have is:
Regex regex = new Regex("^[^/\\#?]{0,1024}$", RegexOptions.Compiled);
if (!regex.IsMatch("\\"))
{
Console.WriteLine("Bad");
}
All of the characters except \ are disallowed. I cannot get \ to work.
Any suggestions on how to support this?
Your regex is fine,
^[^/\\#?]{0,1024}$.However, in C# backslash is an escape character, so a C#
"\\"is a single backslash.Hence for each backslash in your regex, you have to backslash again for C#:
Alternatively, you can use a raw string, meaning backslashes in C# strings remain backslashes (note the
@symbol):