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

댓글

이 블로그의 인기 게시물

Install and run an FTP server using Docker

Using the MinIO API via curl

PYTHONPATH, Python 모듈 환경설정

Elasticsearch Ingest API

오늘의 문장2

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

Fundamentals of English Grammar #1

To switch to a specific tag in a Git repository

You can use Sublime Text from the command line by utilizing the subl command

티베트-버마어파 와 한어파(중국어파)의 어순 비교