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.
Open the WebIDE if it's not already open. You should be in the
~/projectdirectory by default.In the File Explorer on the left, right-click in the empty space and select "New File". Name the file
EmailValidator.java.Open the
EmailValidator.javafile in the editor by clicking on it in the File Explorer.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.javafile: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 thePatternclass, which is part of Java's built-in support for regular expressions.private static final String EMAIL_REGEX = "...";: This line declares a constant variable namedEMAIL_REGEXand 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.
Save the
EmailValidator.javafile (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.
Open the
EmailValidator.javafile in the WebIDE editor if it's not already open.Add the following method inside the
EmailValidatorclass, but outside themainmethod: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 namedisValidEmail.public: Means this method can be accessed from outside the class.static: Means this method belongs to theEmailValidatorclass 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 (trueorfalse).(String email): Specifies that the method takes one argument, aStringnamedemail, which is the email address we want to validate.
return Pattern.matches(EMAIL_REGEX, email);: This is the core of the method. It calls thePattern.matches()method, passing ourEMAIL_REGEXand the inputemailstring. The result of this match (trueorfalse) is then returned by ourisValidEmailmethod.
Now, let's modify the
mainmethod to use our newisValidEmailmethod. Replace the existingmainmethod 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
mainmethod:String testEmail = "test.email@example.com";: We define a sample email address to test.boolean isValid = isValidEmail(testEmail);: We call ourisValidEmailmethod with thetestEmailand store the returned boolean value in theisValidvariable.- The
ifandelseblock checks the value ofisValidand prints a message indicating whether the email is valid or not.
Save the
EmailValidator.javafile (Ctrl+S or Cmd+S).Now, let's compile our updated program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Run the following command:javac EmailValidator.javaIf there are no errors, the compilation was successful.
Finally, run the compiled program using the
javacommand:java EmailValidatorYou 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.
Open the
EmailValidator.javafile in the WebIDE editor.Modify the
mainmethod to test multiple email addresses. Replace the currentmainmethod 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
mainmethod:- We create an array of strings called
testEmailscontaining various email addresses, including both valid and intentionally invalid ones. - We use a
forloop to iterate through each email address in thetestEmailsarray. - Inside the loop, for each
email, we call ourisValidEmailmethod and print the result, just like we did in the previous step.
- We create an array of strings called
Save the
EmailValidator.javafile (Ctrl+S or Cmd+S).Compile the modified program in the Terminal:
javac EmailValidator.javaEnsure there are no compilation errors.
Run the compiled program:
java EmailValidatorObserve the output. You should see a line for each email address in the
testEmailsarray, 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.



