用于 DataAnnotations 中电子邮件验证的 C# 正则表达式 - 双反斜杠
看到这段代码通过数据注释对电子邮件地址进行正则表达式验证。
我无法弄清楚双反斜杠的目的。
对我来说,这意味着电子邮件中必须有反斜杠 - 但我知道这不是它所做的!
[RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email")]
Saw this code for regular expression validation of an email address via data annotations.
I Can't work out the purpose of the double backslash.
To me it's saying there must be a backslash in the email - but I know that this isn't what it is doing!!!
[RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email")]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
反斜杠在 C# 和正则表达式中都是转义字符。因此,在 C# 中,
"\\"
等于单个反斜杠。然后使用生成的反斜杠对.
进行转义,它是一个元字符,因此必须进行转义。但我不知道为什么@
被转义。The backslash is an escape character both in C# and in a regex. So, in C#,
"\\"
equals to a single backslash. The resulting backslash is then used to escape the.
, which is a metacharacter and therefore must be escaped. I don't know why the@
is escaped however.对于 MVC2 模式
然后使用
这将完美地工作..
For MVC2 Pattern
And then use
This will work perfectly..
某些字符在正则表达式中转义时具有特殊含义。例如 \d 表示数字。
在 C# 中,反斜杠具有类似的功能。例如 \n 表示换行符。为了在 C# 中获得反斜杠,您必须使用反斜杠对其进行转义。两个一起相当于字面上的反斜杠。
C# 有一种将字符串表示为文字的方法,因此不使用反斜杠字符 - 在字符串前面添加 @。
Certain characters have special meaning when escaped in a regular expression. For instance \d means a number.
In C# the backslash has a similar function. For instance \n means newline. In order to get a literal backslash in C# you must escape it...with a backslash. Two together is the same as a literal backslash.
C# has a way of denoting a string as literal so backslash characters are not used - prepend the string with @.
双反斜杠是必需的,因为反斜杠是 C# 中的转义字符。另一种选择是
@".+\@.+\..+"
Double-backslash are mandatory because backslash is an Escape character in C#. An alternative could be
@".+\@.+\..+"