Learning
Learning

Reputation: 20001

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?.

Upvotes: 1

Views: 119

Answers (3)

Stefan
Stefan

Reputation: 14870

The backslash is the escape char in c# strings. Technically you have to escape the backslash with another blackslash ("\\") or just add an @ before your string:

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

Upvotes: 2

kufi
kufi

Reputation: 2458

Use @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" so the backslashes will get escaped

Upvotes: 1

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

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+)*";

Upvotes: 4

Related Questions