正規表現で電子メールアドレスを検証する方法

正規表現でメールアドレスを検証する方法

image

メールの正規表現パターン

^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*
      @[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$;

説明

^           #start of the line
  [_A-Za-z0-9-\\+]+ #  must start with string in the bracket [ ], must contains one or more (+)
  (         #   start of group #1
    \\.[_A-Za-z0-9-]+   #     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*            #   end of group #1, this group is optional (*)
    @           #     must contains a "@" symbol
     [A-Za-z0-9-]+      #       follow by string in the bracket [ ], must contains one or more (+)
      (         #         start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #           follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*        #         end of group #2, this group is optional (*)
      (         #         start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #           follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )         #         end of group #3
$           #end of the line

この組み合わせは、メールアドレスが「_A-Za-z0-9- \ +」で始まり、オプションで「。[_ A-Za-z0-9-]」が続き、「@」記号で終わる必要があることを意味します。 電子メールのドメイン名は「A-Za-z0-9-」で始まり、その後に第1レベルのTld(.com、.net)「。[A-Za-z0-9]」が続き、オプションで第2レベルのTldが続く必要があります(.com.au、.com.my)「\。[A-Za-z] \ {2、}」。ここで、第2レベルのTldはドット「。」で始まる必要があります。長さは2文字以上である必要があります。

1. Java正規表現の例

以下は、正規表現を使用してメールアドレスを検証する方法を示すJavaの例です。

EmailValidator.java

package com.example.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {

    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN =
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    /**
     * Validate hex with regular expression
     *
     * @param hex
     *            hex for validation
     * @return true valid hex, false invalid hex
     */
    public boolean validate(final String hex) {

        matcher = pattern.matcher(hex);
        return matcher.matches();

    }
}

3. 無効なメール

1. 例–「@」記号
2が含まれている必要があります。 example @ .com.my – tldはドット「。」
3で始めることはできません。 [email protected] –「。a」は有効なtldではありません。最後のtldには少なくとも2文字
4が含まれている必要があります。 example123 @ .com – tldはドット「。」
5で始めることはできません。 example123 @ .com.com – tldはドット「。」
6で始めることはできません。 。[email protected] –電子メールの最初の文字をドット「。」で始めることはできません。
7。 example()@gmail.com – email’s is only allow character, digit, underscore and dash
8. [email protected]%
.com –メールのTLDは、文字と数字のみを許可します
9。 [email protected] – double dots “.” are not allow
10. [email protected] – email’s last character can not end with dot “.”
11. [email protected][email protected] – double “@” is not allow
12. [email protected].1a -email’s tld which has two characters can not contains digit

4. 単体テスト

これがtestNGを使用した単体テストです。

EmailValidatorTest.java

package com.example.regex;

import org.testng.Assert;
import org.testng.annotations.*;

/**
 * Email validator Testing
 *
 * @author example
 *
 */
public class EmailValidatorTest {

    private EmailValidator emailValidator;

    @BeforeClass
    public void initData() {
        emailValidator = new EmailValidator();
    }

    @DataProvider
    public Object[][] ValidEmailProvider() {
        return new Object[][] { { new String[] { "[email protected]",
            "[email protected]", "[email protected]",
            "[email protected]", "[email protected]",
            "[email protected]", "[email protected]",
            "[email protected]", "[email protected]",
            "[email protected]" } } };
    }

    @DataProvider
    public Object[][] InvalidEmailProvider() {
        return new Object[][] { { new String[] { "example", "[email protected]",
            "[email protected]", "[email protected]", "[email protected]",
            "[email protected]", "example()*@gmail.com", "[email protected]%*.com",
            "[email protected]", "[email protected]",
            "[email protected]@gmail.com", "[email protected]" } } };
    }

    @Test(dataProvider = "ValidEmailProvider")
    public void ValidEmailTest(String[] Email) {

        for (String temp : Email) {
            boolean valid = emailValidator.validate(temp);
            System.out.println("Email is valid : " + temp + " , " + valid);
            Assert.assertEquals(valid, true);
        }

    }

    @Test(dataProvider = "InvalidEmailProvider", dependsOnMethods = "ValidEmailTest")
    public void InValidEmailTest(String[] Email) {

        for (String temp : Email) {
            boolean valid = emailValidator.validate(temp);
            System.out.println("Email is valid : " + temp + " , " + valid);
            Assert.assertEquals(valid, false);
        }
    }
}

これがユニットテストの結果です。

Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : [email protected] , true
Email is valid : example , false
Email is valid : [email protected] , false
Email is valid : [email protected] , false
Email is valid : [email protected] , false
Email is valid : [email protected] , false
Email is valid : [email protected] , false
Email is valid : example()*@gmail.com , false
Email is valid : [email protected]%*.com , false
Email is valid : [email protected] , false
Email is valid : [email protected] , false
Email is valid : [email protected]@gmail.com , false
Email is valid : [email protected] , false
PASSED: ValidEmailTest([Ljava.lang.String;@15f48262)
PASSED: InValidEmailTest([Ljava.lang.String;@789934d4)

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================