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

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

问题描述

我有一个正则表达式来验证我的邮件地址,如下所示:

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})(]?)

这工作得很好,但只允许输入一封电子邮件.现在我想扩展它并允许添加多个邮件地址(就像 MS 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

现在我已经搜索并找到了这个:

Now I've searched and found this one:

([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 replace 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 change this group:

(s*;s*|s*$)

通过这个:

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

重要提示:正如 Martin 在评论中所述,如果在正确的电子邮件地址列表之前或之后有其他文本,验证将不会失败.所以它可以作为电子邮件搜索器".要使其作为验证器工作,您需要在正则表达式的开头添加 ^,并在末尾添加 $.这将确保表达式匹配所有文本.所以完整的正则表达式是:

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 regex 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* 以容忍列表开头的空白,如下所示.IE.包括 ^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天全站免登陆