简体   繁体   中英

Regex Email - Ignore leading and trailing spaces?

We are using the following to do an email validation in 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: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()

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 !

All email addresses have to be validated from the point of view of this regex...

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

Just warning you.

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