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.".

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

Sparse encoder

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

Nginx Openssl 설정

To monitor logs for a Kubernetes CronJob

Sort the distinct values by their count in descending order using the DataFrame API

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

[Ubuntu] *.deb 파일 설치 방법

Node.js memory limit, 노드 메모리 제한하기