开发者

Fix Regular Expression for Emails to Not allow Consecutive Periods

my regular Expressions are pretty bad so I thought would look for some help on this.

I have a regular expression:

/[a-z0-9!#$%&'*+/=?开发者_如何学编程^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

and it works for most cases of my email validation however it allows this one through:

test..testing@gmail.com

How would I alter the above Regular Expression to not allow consecutive periods anywhere throughout the string?

Thanks.


To avoid matching two consecutive dots you can add a negative lookahead at the beginning of your regular expression:

/^(?!.*\.{2})[a-z0-9etc...
 ------------

It will fail to match if there are two consecutive periods anywhere in the string and it doesn't require any other modifications to your original regular expression.

However it seems a bad idea as your regular expression isn't correct in the first place. If you insist on using regular expressions to validate email addresses, try this:

  • Mail::RFC822::Address: regexp-based address validation


Don't. That email address is functional in practice (albeit technically invalid according to the relevant RFC).

Top tip: do not "validate" email addresses with regex as you will get it wrong.


Don't try to invent the wheel ;)

For instance, see here:

http://www.regular-expressions.info/email.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜