Validator of email address in Java

In Java, you can use the java.util.regex package to validate an email address. Here's an example code snippet to do so:

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

public class EmailValidator {
    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_REGEX = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_REGEX, Pattern.CASE_INSENSITIVE);
    }

    public boolean validateEmail(String email) {
        matcher = pattern.matcher(email);
        return matcher.matches();
    }
}

In this code, we create an EmailValidator class that compiles a regular expression pattern for validating email addresses. The regular expression pattern used here is a common one that matches most valid email addresses. The validateEmail method takes an email address as a parameter and returns a boolean value indicating whether the email address is valid or not.

To use this class, you can create an instance of EmailValidator and call the validateEmail method with the email address you want to validate. Here's an example:

EmailValidator validator = new EmailValidator();
String email = "john.doe@example.com";
if (validator.validateEmail(email)) {
    System.out.println(email + " is a valid email address.");
} else {
    System.out.println(email + " is not a valid email address.");
}

In this example, we create an instance of EmailValidator and pass the email address "john.doe@example.com" to the validateEmail method. If the email address is valid, the program will output "john.doe@example.com is a valid email address."; otherwise, it will output "john.doe@example.com is not a valid email address.".

댓글

이 블로그의 인기 게시물

CDPEvents in puppeteer

Using the MinIO API via curl

vsftpd default directory

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

리눅스의 부팅과정 (프로세스, 서비스 관리)

Install and run an FTP server using Docker

MySQL GRANT

리눅스 (cron - 주기적 작업실행 데몬)