简体   繁体   English

正则表达式电子邮件 - 忽略前导和尾随空格?

[英]Regex Email - Ignore leading and trailing spaces?

We are using the following to do an email validation in ASP.NET: 我们使用以下内容在ASP.NET中进行电子邮件验证:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

How can this be modified to ignore leading and trailing spaces? 如何修改它以忽略前导和尾随空格?

The actual trimming we handle in code on postback but the validator is triggering as being invalid if the user has an extra space often due to copying and paste. 我们在回发代码中处理的实际修剪但是如果用户通常由于复制和粘贴而具有额外空间,则验证器将被触发为无效。

您可以在模式之前和之后放置\\s* ,它应该正常工作。

将您想要的内容分组到命名捕获中,然后在捕获之前和之后允许空格

\s*(?<email>\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*)\s*

只需在将其传递给验证器之前进行修剪。

In case of ASP.NET the following works: 在ASP.NET的情况下,以下工作:

<asp:TextBox runat="server" ID="EmailAddress" />
<asp:RegularExpressionValidator ValidationExpression="\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*" runat="server" ControlToValidate="EmailAddress" Text="*" ErrorMessage="Email is not valid"  />

Allows a variety of emails like: 允许各种电子邮件,例如:

"some@one.com"
"  some@one.com  "
"so_me@one.co.uk"
" a.s-d__+f@asd.as.as "

etc 等等

Make sure you strip the white spaces in your code like so: 确保在代码中删除空格,如下所示:

VB Dim Email as string = EmailAddress.Text.Trim() VB Dim Email as string = EmailAddress.Text.Trim()

C# string Email = EmailAddress.Text.Trim(); C# string Email = EmailAddress.Text.Trim();

I was going to "answer" this as a simple comment, but the real answer to your question is that there is no answer . 我打算“回答”这个简单的评论,但你问题的真正答案是没有答案

Why? 为什么?

Because any email address with space or whitespaces before or after it, is an invalid email address. 因为任何在其之前或之后有空格或空格的电子邮件地址都是无效的电子邮件地址。

You try and pass an email address with whitespace chars around it into an SMPTP control for example, and try and send it, it will fail ! 您尝试将带有空格字符的电子邮件地址传递给SMPTP控件,例如,尝试发送它, 它将失败

All email addresses have to be validated from the point of view of this regex... 所有电子邮件地址都必须从此正则表达式的角度进行验证...

\\w+([-+.']\\w+) @\\w+([-.]\\w+) .\\w+([-.]\\w+)* \\ w +([ - +。'] \\ w +) @ \\ w +([ - 。] \\ w +) 。\\ w +([ - 。] \\ w +)*

or even this 甚至这个

/.+@.+/ /.+@.+/

Anything else is an invalid email address. 其他任何东西都是无效的电子邮件地址。

Really the way around it is to TRIM() the string before passing into an email control to use it. 真正的方法是将TRIM()字符串传递给电子邮件控件以使用它。

Just warning you. 只是警告你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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