简体   繁体   中英

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

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

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

使用@"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"这样反斜杠将被转义

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM