电子邮件地址的正则表达式

时间:2014-08-27 10:54:26

标签: php html regex

我在这段代码上工作了几个小时。我想用正则表达式代码处理这些邮件地址:

text@text(Dot)de
text(@)text(Dot)de
text(at)text(Dot)de
text|at|text(Dot)de

text@text.de
text(@)text.de
text(at)text.de
text|at|text.de

text @ text.de
text (@) text.de
text (at) text.de
text |at| text.de
你能为我提供一些东西吗?我最终得到了:[-0-9a-zA-Z.+_]+(@|\(@\)|at)+[-0-9a-zA-Z.+_]+\.(de|com|net|org)

但它没有用:(

3 个答案:

答案 0 :(得分:3)

我要做的是以下内容:

为电子邮件匹配创建一个界面:

interface IEmailMatcher {
    function matches($rawEmail);
    function toEmail($rawEmail);
}

然后实现目前已知的每一种可能性:

//Matcher for regular emails
class BasicEmailMatcher implements IEmailMatcher {
    public function matches($rawEmail) {
        // PHP has a built in for this
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    public function toEmail($rawEmail) {
        // If we passed the filter, it doesn't need any transformation.
        return $rawEmail;
    }
}

另一个:

class OtherEmailMatcher implements IEmailMatcher {
    public function matches($rawEmail) {
        return preg_match(/*pattern for one format*/, $rawEmail);
    }

    public function toEmail($rawEmail) {
        // return the funky looking email transformed to normal email.
    }
}

然后验证的地方,只需创建一个包含所有匹配器的数组:

$matchers = [new BasicEmailMatcher(), new OtherEmailMatcher(), ...];
foreach($matchers as $matcher) {
    if($matcher->matches($inputEmail)){
        // format it back to normal.
        $email = $matcher->toEmail($inputEmail); 
    }
}

这种方式可扩展清晰易于理解,如果您需要添加更多这些(或需要删除)一个后来),但可能有点慢。

答案 1 :(得分:1)

您可以像这样修改您的模式:

/([\-0-9a-zA-Z\.\+_]+\s?(?:@|\(at\)|\|at\||\(@\))\s?+[\-0-9a-zA-Z\.\+_]+(?:\.|\(Dot\))(?:de|com|net|org))/g

演示:http://regex101.com/r/vY0rD6/1

答案 2 :(得分:1)

也可以使用conditionals:请参阅example at regex101

$pattern = '~
[-+.\w]+                # [-0-9a-zA-Z.+_]+
(\s*)                   # optional: any amount of spaces (-> $1)
(?:(\()|(\|))?          # conditional $2: if opening ( | $3: if |
(@|at)                  # @|at  
(?(2)\)|(?(3)\|))       # if $2 -> ), if $3 -> | 
\1                      # amount of spaces, captured in $1
[-+.\w]+
(?:\.|\(Dot\))(?:de|com|net|org)~x';

使用x (PCRE_EXTENDED) modifier进行评论。

Test at eval.in / SO Regex FAQ

相关问题