Regular expression to allow backslash in C#

Backslashes need to be escaped in regular expressions – and they also need to be escaped in C#, unless you use verbatim string literals. So either of these should work:

var regexItem = new Regex(@"^[a-zA-Z0-9\\ ]*$");
var regexItem = new Regex("^[a-zA-Z0-9\\\\ ]*$");

Both of these ensure that the following string content is passed to the Regex constructor:

^[a-zA-Z0-9\\ ]*$

The Regex code will then see the double backslash and treat it as “I really want to match the backslash character.”

Basically, you always need to distinguish between “the string contents you want to pass to the regex engine” and “the string literal representation in the source code”. (This is true not just for regular expressions, of course. The debugger doesn’t help by escaping in Watch windows etc.)

EDIT: Now that the question has been edited to show that you originally had three backslashes, that’s just not valid C#. I suspect you were aiming for “a string with three backslashes in” which would be either of these:

var regexItem = new Regex(@"^[a-zA-Z0-9\\\ ]*$");
var regexItem = new Regex("^[a-zA-Z0-9\\\\\\ ]*$");

… but you don’t need to escape the space as far as the regular expression is concerned.

Leave a Comment