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

댓글

이 블로그의 인기 게시물

To switch to a specific tag in a Git repository

kafka polling vs listen

Create topic on Kafka with partition count, 카프카 토픽 생성하기

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

Scan an HBase table with a prefix filter

Joining an additional control plane node to an existing Kubernetes cluster

max_active_runs of Airflow

Vespa vs Milvus

urllib3 with proxy settings

The Consumer.wakeup() method in the Kafka Consumer