Learning Learning - 1 month ago 212
C# Question

Why doesn't my code compile?

I am using regular expression in code behind file and defining string as

string ValEmail = "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

if (Regex.IsMatch(email, "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
{ }
else
{ }


It gives me warning and does not compile. How can I define such string combination?.

Answer Source

In C# the backslash is a special character, if it is to represent a backslash we need to inform the compiler as such.

This can be achieved by escaping it with a backslash:

string ValEmail = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

Or using an @ prefix when constructing the string:

string ValEmail = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";