How to Check If a String Matches an Email Format in Java

JavaBeginner
Practice Now

Introduction

In this lab, you will learn how to validate if a given string matches a standard email format in Java using regular expressions. We will define a suitable regex pattern, utilize the Pattern.matches() method for validation, and test our implementation with various valid and invalid email addresses to ensure it functions correctly. This hands-on exercise will provide practical experience with Java's regex capabilities for string pattern matching.

Define Email Regex Pattern

In this step, we will start by defining the regular expression pattern that we will use to validate email addresses. Regular expressions, often shortened to "regex" or "regexp", are sequences of characters that define a search pattern. They are extremely powerful for pattern matching and manipulation of strings.

For email validation, a regex pattern helps us check if a given string follows the standard format of an email address (e.g., username@domain.com). While a perfect regex for all possible valid email addresses is very complex, we can define a pattern that covers most common and valid formats.

We will create a new Java file to hold our code.

  1. Open the WebIDE if it's not already open. You should be in the ~/project directory by default.

  2. In the File Explorer on the left, right-click in the empty space and select "New File". Name the file EmailValidator.java.

  3. Open the EmailValidator.java file in the editor by clicking on it in the File Explorer.

  4. Now, let's add the basic structure of our Java class and define the regex pattern. Copy and paste the following code into the EmailValidator.java file:

    import java.util.regex.Pattern;
    
    public class EmailValidator {
    
        // Email regex pattern
        private static final String EMAIL_REGEX =
                "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    
        public static void main(String[] args) {
            // We will add code here in the next steps
        }
    }

    Let's briefly look at the new parts:

    • import java.util.regex.Pattern;: This line imports the Pattern class, which is part of Java's built-in support for regular expressions.
    • private static final String EMAIL_REGEX = "...";: This line declares a constant variable named EMAIL_REGEX and assigns our regular expression pattern to it.
      • ^: Matches the beginning of the string.
      • [a-zA-Z0-9_+&*-]+: Matches one or more alphanumeric characters or _, +, &, *, -. This is for the username part.
      • (?:\\.[a-zA-Z0-9_+&*-]+)*: Matches zero or more occurrences of a dot followed by more username characters. This allows for dots in the username (e.g., first.last).
      • @: Matches the literal "@" symbol.
      • (?:[a-zA-Z0-9-]+\\.)+: Matches one or more occurrences of alphanumeric characters or - followed by a dot. This is for the domain name (e.g., domain.).
      • [a-zA-Z]{2,7}: Matches 2 to 7 alphabetic characters for the top-level domain (e.g., com, org, country codes).
      • $: Matches the end of the string.

    Don't worry if the regex pattern looks complicated. Understanding every detail of complex regex patterns takes time and practice. For now, focus on the fact that this string defines the rule for what a valid email address looks like.

  5. Save the EmailValidator.java file (Ctrl+S or Cmd+S).

You have now successfully created the Java file and defined the regular expression pattern for email validation. In the next step, we will use this pattern to validate actual email addresses.

Use Pattern.matches() for Email Validation

In this step, we will learn how to use the Pattern.matches() method in Java to check if a given string matches our defined email regex pattern. The Pattern.matches(regex, input) method is a convenient way to perform a simple match of an entire input string against a regular expression. It returns true if the entire input string matches the regex, and false otherwise.

We will add a new method to our EmailValidator class to perform this validation.

  1. Open the EmailValidator.java file in the WebIDE editor if it's not already open.

  2. Add the following method inside the EmailValidator class, but outside the main method:

    public static boolean isValidEmail(String email) {
        return Pattern.matches(EMAIL_REGEX, email);
    }

    Let's look at this new method:

    • public static boolean isValidEmail(String email): This declares a new method named isValidEmail.
      • public: Means this method can be accessed from outside the class.
      • static: Means this method belongs to the EmailValidator class itself, not to a specific object of the class. We can call it directly using the class name (e.g., EmailValidator.isValidEmail(...)).
      • boolean: Indicates that this method will return a boolean value (true or false).
      • (String email): Specifies that the method takes one argument, a String named email, which is the email address we want to validate.
    • return Pattern.matches(EMAIL_REGEX, email);: This is the core of the method. It calls the Pattern.matches() method, passing our EMAIL_REGEX and the input email string. The result of this match (true or false) is then returned by our isValidEmail method.
  3. Now, let's modify the main method to use our new isValidEmail method. Replace the existing main method with the following code:

    public static void main(String[] args) {
        String testEmail = "test.email@example.com";
        boolean isValid = isValidEmail(testEmail);
    
        if (isValid) {
            System.out.println(testEmail + " is a valid email address.");
        } else {
            System.out.println(testEmail + " is not a valid email address.");
        }
    }

    In this updated main method:

    • String testEmail = "test.email@example.com";: We define a sample email address to test.
    • boolean isValid = isValidEmail(testEmail);: We call our isValidEmail method with the testEmail and store the returned boolean value in the isValid variable.
    • The if and else block checks the value of isValid and prints a message indicating whether the email is valid or not.
  4. Save the EmailValidator.java file (Ctrl+S or Cmd+S).

  5. Now, let's compile our updated program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Run the following command:

    javac EmailValidator.java

    If there are no errors, the compilation was successful.

  6. Finally, run the compiled program using the java command:

    java EmailValidator

    You should see output indicating whether the test email is valid based on our regex pattern.

    test.email@example.com is a valid email address.

You have now successfully used the Pattern.matches() method to validate an email address using your defined regex pattern. In the next step, we will test with different valid and invalid email addresses.

Test with Valid and Invalid Emails

In this final step, we will test our EmailValidator with a few examples of both valid and invalid email addresses to see how our regex pattern and Pattern.matches() method handle them. This will help us understand the behavior of our validation logic.

  1. Open the EmailValidator.java file in the WebIDE editor.

  2. Modify the main method to test multiple email addresses. Replace the current main method with the following code:

    public static void main(String[] args) {
        String[] testEmails = {
            "test.email@example.com",       // Valid
            "another_test+alias@sub.domain.co.uk", // Valid
            "invalid-email",                // Invalid (missing @)
            "invalid@domain",               // Invalid (missing top-level domain)
            "invalid@domain.",              // Invalid (missing top-level domain)
            "invalid@domain.c",             // Invalid (top-level domain too short)
            "invalid@domain.abcdefgh",      // Invalid (top-level domain too long)
            "@domain.com",                  // Invalid (missing username)
            "test@.com"                     // Invalid (missing domain name)
        };
    
        for (String email : testEmails) {
            boolean isValid = isValidEmail(email);
    
            if (isValid) {
                System.out.println(email + " is a valid email address.");
            } else {
                System.out.println(email + " is not a valid email address.");
            }
        }
    }

    In this updated main method:

    • We create an array of strings called testEmails containing various email addresses, including both valid and intentionally invalid ones.
    • We use a for loop to iterate through each email address in the testEmails array.
    • Inside the loop, for each email, we call our isValidEmail method and print the result, just like we did in the previous step.
  3. Save the EmailValidator.java file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac EmailValidator.java

    Ensure there are no compilation errors.

  5. Run the compiled program:

    java EmailValidator

    Observe the output. You should see a line for each email address in the testEmails array, indicating whether our validator considers it valid or not based on the regex pattern.

    test.email@example.com is a valid email address.
    another_test+alias@sub.domain.co.uk is a valid email address.
    invalid-email is not a valid email address.
    invalid@domain is not a valid email address.
    invalid@domain. is not a valid email address.
    invalid@domain.c is not a valid email address.
    invalid@domain.abcdefgh is not a valid email address.
    @domain.com is not a valid email address.
    test@.com is not a valid email address.

By testing with different inputs, you can see how the regex pattern and the Pattern.matches() method work together to validate email addresses. Remember that while this regex covers many common cases, validating all possible email formats according to strict standards can be much more complex.

You have now successfully implemented and tested a basic email validation mechanism using Java's regular expression capabilities.

Summary

In this lab, we began by setting up our Java environment and creating a new file EmailValidator.java. We then defined a regular expression pattern (EMAIL_REGEX) specifically designed for validating email addresses. This pattern, stored as a constant string, utilizes Java's java.util.regex.Pattern class to enable powerful string matching capabilities. This initial step lays the foundation for implementing email validation logic in subsequent steps.