【发布时间】:2020-02-09 13:33:38
【问题描述】:
我尝试创建一个 PCRE 正则表达式来从大量文本中捕获电子邮件地址。我想出的当前正则表达式是:
(?:[^\w]|^)([a-z0-9+_\-\.]+[^\.]@(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?)(?:[^\w]|$)
这个正则表达式太慢了(Q方,为什么这么慢?是非捕获组对性能影响很大吗?)。我知道在所有有效电子邮件的覆盖率和性能之间会有一些权衡,我的目标是获得最常见的格式,例如:
very.common@example.com
disposable.style.email.with+symbol@example.com
other.email-with-hyphen@example.coma
fully-qualified-domain@example.com
user.name+tag+sorting@example.com
example-indeed@strange-example.com
mailhost!username@example.org
user%example.com@example.org
但不是无效地址,例如:
Abc.example.com
A@b@c@example.com
A.....example.com
例如 A@b@c@example.com 无效,但我不希望正则表达式捕获 A@b@c@example.com "c@example.com “ 还! 我试图接近 Negative lookahead 来检查是否存在 @ 例如 (?
【问题讨论】:
-
这是一个更广泛的匹配,但你可以试试
(?<!\S)[^\s@]+@[^\s@]+\.[^\s@.]+(?!\S)regex101.com/r/CTw01I/1 -
regex for RFC822 email address。验证电子邮件地址的最佳方法是发送消息并检查返回值。