【问题标题】:Regular expression to match email except for specific email address(es)用于匹配电子邮件的正则表达式,特定电子邮件地址除外
【发布时间】:2017-10-10 00:15:12
【问题描述】:

我需要一个匹配电子邮件地址的正则表达式,但从匹配项中排除特定的电子邮件地址

例如不匹配(从匹配中排除这些地址);

sponge.bob@example.com
jim.bob@example.com
billy.bob@example.com

匹配所有其他电子邮件地址(包括任何其他有效的电子邮件地址);

test@example.com
no.body@example.com
another.test.email@example.com
and.another.one@example.com.au

我尝试使用否定的lookbehind 表达式,但不知道如何使其工作(如果甚至可以通过该方法)。能够指定多个排除的电子邮件将是有益的,但至少需要排除一个。

谢谢

【问题讨论】:

  • 你想匹配什么,你不想匹配什么?编辑您的问题,使其更具体。

标签: regex


【解决方案1】:
(?:^|(?<=\s))(?!sponge\.bob@example\.com|jim\.bob@example\.com|billy\.bob@example\.com)(\w[\w\.]*@\w+\.[\w\.]+)\b

查看演示here.


解释

(?:^|(?<=\s))                   //appears at start of line or after space
(?!                             //Don't match if it starts with the below
sponge\.bob@example\.com|
jim\.bob@example\.com|
billy\.bob@example\.com
)                               //End exclusions
(                               //Capture group for emails, you don't need this
\w                              //Start with [A-Za-z0-9_]
[\w\.]*                         //Zero or more of [w\.]
@
\w+                             //Start with one or more [A-Za-z0-9_]
\.                              //Forces to have atleast one dot
[\w\.]+                         //followed by one or more of [\w\.]
)                               //End capture group for emails, remove it with the matching group
\b                              //Should end with word boundary.

【讨论】:

  • 令人印象深刻,您能否解释一下为什么这部分使以下表达式起作用 (?:^|(?
  • 它只是强制电子邮件地址从行首^ 或空格后\s 开始。否则它将匹配bob@example.com,即使它来自sponge.bob@example.com
  • 实际上,这让我认为如果我们强制使用空格或行尾作为电子邮件地址的尾随边界,它会很健壮。我会把它留给你。
  • 目前它是一个松散的\b,所以它将匹配a.b@c.d.中的a.b@c.d
  • 另外我会在\w 中包含一个-,因为我认为它是电子邮件地址中的一个有效字符,我不确定。
猜你喜欢
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 2018-01-08
相关资源
最近更新 更多