【问题标题】:Match all email addresses belonging to a specific domain and its subdomains匹配属于特定域及其子域的所有电子邮件地址
【发布时间】:2012-09-07 02:21:23
【问题描述】:

我希望匹配来自特定域的所有电子邮件地址。

来自example.comfoo.example.com 的任何电子邮件都应该匹配,其他所有邮件都应该被拒绝。为此,我可以进行一些基本的字符串匹配来检查给定的字符串是否以example.com 结尾或包含example.com,这可以正常工作,但这也意味着fooexample.com 之类的东西会通过。

因此,基于上述要求,我开始研究一种可以传递域及其子域的模式。我能够想出以下正则表达式模式:

`/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.example.com\b/i`

这仅匹配子域,但我在“How to match all email addresses at a specific domain using regex?”看到了处理主域的模式。

有没有办法将这两者结合成适用于any address from example.com 的东西。

【问题讨论】:

    标签: ruby regex email string-matching


    【解决方案1】:

    怎么样

    /\b(?:(?![_.-])(?!.*[_.-]{2})[a-z0-9_.-]+(?<![_.-]))@(?:(?!-)(?!.*--)[a-z0-9-]+(?<!-)\.)*example\.com\b/i
    

    【讨论】:

      【解决方案2】:

      这也将匹配 'tagged' 和 'tagged-subdomain' 邮件,如 a+b@example.com 和 a+b@i.example.com

      (([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@(?:(?!-)(?!.*--)[a-z0-9-]+(?<!-)\.)*example\.com\b
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        我建议阅读“Stop Validating Email Addresses With Your Complex Regex”。

        从那时起,我会寻找:

        /@.*\bexample\.com/
        

        例如:

        %w[foo@example.com foo@barexample.com foo@subdomain.example.com].grep(/@.*\bexample\.com/)
        => ["foo@example.com", "foo@subdomain.example.com"]
        

        很容易得到一个维护噩梦的正则表达式,并且不能满足您的需要。我强烈建议保持简单。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-20
          • 1970-01-01
          • 1970-01-01
          • 2010-12-30
          • 2011-06-14
          • 1970-01-01
          • 2016-07-16
          • 1970-01-01
          相关资源
          最近更新 更多