Learning Learning - 10 months ago 330
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+)*"))
{ }
{ }

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+)*";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download