正则表达式用于验证多个电子邮件的地址 [英] Regex for validating multiple E-Mail-Addresses

查看:161
本文介绍了正则表达式用于验证多个电子邮件的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了验证我的邮件地址,这样的正则表达式:

I got a Regex that validates my mail-addresses like this:

([A-ZA-Z0-9_\-\\ \\。] +)@((\ [[0-9] {1,3} \。[0-9] {1,3} \。[0-9] {1,3} \。 )|(([A-ZA-Z0-9\ - ] + \。)+))([A-ZA-Z] {2,4} | [0-9] {1,3})( \])

这工作完全正常,但只允许输入一个电子邮件。现在我想以扩展并允许添加多个邮件地址(就像微软的Outlook,例如)以分号作为邮件分离器。

This works perfectly fine, but only allows one e-mail to be entered. Now I wanted to extend that and allow multiple mail-addresses to be added (just like MS Outlook, for example) with a semicolon as a mail-splitter.

mail1@tld.com; mail2@tld.com; mail3@tld.com

这一个:

([A-ZA-Z0-9 ._%+ - ] + @ [A-ZA-Z0-9。 - ] + \ [A-ZA-Z] {2,4}(; | $))

这适用于一个点,但可悲的需要是在邮件的最​​后一个分号:

This works on one point, but sadly requires a semicolon at the end of a mail:

mail1@tld.com;

这是不是我想要的,当用户只输入一个电子邮件。

This is not what I want when the user only enters one e-mail.

如何延长我的正则表达式以上(第一个),以允许添加多个邮件地址,同时让他们通过一个分号劈裂?

How can I extend my regex above (the first one) to allow multiple mail-addresses to be added while let them be splitted through a semicolon?

推荐答案

这是你原来的表情,更改,以便它可以用分号(可选)除了分号空格分开多封电子邮件。它还允许不分号结束一个电子邮件地址。

This is your original expression, changed so that it allows several emails separated by semicolon and (optionally) spaces besides the semicolon. It also allows a single email address that doesn't end in semicolon.

这允许空白项(没有电子邮件地址)。你可以改变最终通过* +,要求至少有一个地址。

This allows blank entries (no email addresses). You can change the final * by + to require at least one address.

(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*

如果你需要允许逗号,除了分号,你可以恰克本组:

If you need to allow comma, apart from semicolon, you can chage this group:

(\s*;\s*|\s*$)

本之一:

(\s*(;|,)\s*|\s*$)

重要提示:在马丁的注释状态,如果有正确的电子邮件地址列表之前或之后附加文本,确认不会失败。所以,它的工作作为一个邮件搜索。为了让,因为你需要在末尾添加 ^ 的正则表达式的开始, $ 的验证工作。这将确保所有表达的文本相匹配。因此,全reex将是:

Important note: as states in the comment by Martin, if there are additional text before or after the correct email address list, the validation will not fail. So it would work as an "email searcher". To make it work as a validator you need to add ^ at the beginning of the regex, and $ at the end. This will ensure that the expression matches all the text. So the full reex would be:

^(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*$

您可以添加额外的 \s * ^ 在列表的开头容忍的空白,像这样。即包括 ^ \s * 而不是简单地 ^ 表达已经在为是年底容忍空白。

You can add an extra \s* after the ^ to tolerate blanks at the beginning of the list, like this. I.e. include ^\s* instead of simply ^ The expression already tolerates blanks at the end as is.

这篇关于正则表达式用于验证多个电子邮件的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆