0

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?

3 Answers 3

4

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#:

Regex regex = new Regex("^[^/\\\\#?]{0,1024}$", RegexOptions.Compiled);

Alternatively, you can use a raw string, meaning backslashes in C# strings remain backslashes (note the @ symbol):

Regex regex = new Regex(@"^[^/\\#?]{0,1024}$", RegexOptions.Compiled);
2

You were close, you need to escape the backslash:

^[^/\\#?]{0,1024}$

Even though you do not need to escape special characters inside a character class you do need to escape the escape character itself.

1

Try two forward slashes.

^[^/\\#?]{0,1024}$

In C++, the forward slash is reserved for escape characters, like \n. To make a literal forward slash, use \\.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.