eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this tutorial, we’ll learn how to validate email addresses in Java using regular expressions.

2. Email Validation in Java

Email validation is required in nearly every application that has user registration in place.

An email address is divided into three main parts: the local part, an @ symbol, and a domain. For example, if “[email protected]” is an email, then:

  • local part = username
  • @ = @
  • domain = domain.com

It can take a lot of effort to validate an email address through string manipulation techniques, as we typically need to count and check all the character types and lengths. But in Java, by using a regular expression, it can be much easier.

As we know, a regular expression is a sequence of characters to match patterns. In the following sections, we’ll see how email validation can be performed by using several different regular expression methods.

3. Simple Regular Expression Validation

The simplest regular expression to validate an email address is ^(.+)@(\S+) $.

It only checks the presence of the @ symbol in the email address. If present, then the validation result returns true, otherwise, the result is false. However, this regular expression doesn’t check the local part and domain of the email.

For example, according to this regular expression, [email protected] will pass the validation, but username#domain.com will fail the validation.

Let’s define a simple helper method to match the regex pattern:

public static boolean patternMatches(String emailAddress, String regexPattern) {
    return Pattern.compile(regexPattern)
      .matcher(emailAddress)
      .matches();
}

We’ll also write the code to validate the email address using this regular expression:

@Test
public void testUsingSimpleRegex() {
    emailAddress = "[email protected]";
    regexPattern = "^(.+)@(\\S+)$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

The absence of the @ symbol in the email address will also fail the validation.

4. Strict Regular Expression Validation

Now let’s write a more strict regular expression that will check the local part, as well as the domain part of the email:

^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$

The following restrictions are imposed in the email address’ local part by using this regex:

  • It allows numeric values from 0 to 9.
  • Both uppercase and lowercase letters from a to z are allowed.
  • Allowed are underscore “_”, hyphen “-“, and dot “.”
  • Dot isn’t allowed at the start and end of the local part.
  • Consecutive dots aren’t allowed.
  • For the local part, a maximum of 64 characters are allowed.

Restrictions for the domain part in this regular expression include:

  • It allows numeric values from 0 to 9.
  • We allow both uppercase and lowercase letters from a to z.
  • Hyphen “-” and dot “.” aren’t allowed at the start and end of the domain part.
  • No consecutive dots.

We’ll also write the code to test out this regular expression:

@Test
public void testUsingStrictRegex() {
    emailAddress = "[email protected]";
    regexPattern = "^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@" 
        + "[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

So some of the email addresses that will be valid via this email validation technique are:

Here’s a shortlist of some email addresses that will be invalid via this email validation:

5. Regular Expression for Validation of Non-Latin or Unicode Characters Email

The regex that we just saw in the previous section will work well for email addresses written in the English language, but it won’t work for Non-Latin email addresses.

So we’ll write a regular expression that we can use to validate unicode characters as well:

^(?=.{1,64}@)[\\p{L}0-9_-]+(\\.[\\p{L}0-9_-]+)*@[^-][\\p{L}0-9-]+(\\.[\\p{L}0-9-]+)*(\\.[\\p{L}]{2,})$

We can use this regex for validating Unicode or Non-Latin email addresses to support all languages.

As we can see, this regex is similar to the strict regex that we built in the previous section, except that we changed the “A-Za-Z” part with “\\p{L}”. This is to enable the support for Unicode characters.

Let’s check this regex by writing the test:

@Test
public void testUsingUnicodeRegex() {
    emailAddress = "用户名@领域.电脑";
    regexPattern = "^(?=.{1,64}@)[\\p{L}0-9_-]+(\\.[\\p{L}0-9_-]+)*@" 
        + "[^-][\\p{L}0-9-]+(\\.[\\p{L}0-9-]+)*(\\.[\\p{L}]{2,})$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

This regex not only presents a more strict approach to validate email addresses, but it also supports Non-Latin characters as well.

6. Regular Expression by RFC 5322 for Email Validation

Instead of writing a custom regex to validate email addresses, we can use one provided by the RFC standards.

The RFC 5322, which is an updated version of RFC 822, provides a regular expression for email validation.

Let’s check it out:

^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$

As we can see, it’s a very simple regex that allows all the characters in the email.

However, it doesn’t allow the pipe character (|) and single quote (‘), as these present a potential SQL injection risk when passed from the client site to the server.

Let’s write the code to validate an email with this regex:

@Test
public void testUsingRFC5322Regex() {
    emailAddress = "[email protected]";
    regexPattern = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

7. Regular Expression to Check Characters in the Top-Level Domain

We’ve written regex to verify the email address’ local and domain parts. Now we’ll also write a regex that checks the top-level domain of the email.

The below regular expression validates the top-level domain part of the email address:

^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$

This regex basically checks whether the email address has only one dot, and that there’s a minimum of two and maximum of six characters present in the top-level domain.

We’ll also write some code to verify the email address by using this regex:

@Test
public void testTopLevelDomain() {
    emailAddress = "[email protected]";
    regexPattern = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*" 
        + "@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

8. Regular Expression to Restrict Consecutive, Trailing, and Leading Dots

Now let’s write a regex that will restrict the usage of dots in the email addresses:

^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&’*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$

The above regular expression is used to restrict consecutively, leading, and trailing dots. Thus, an email can contain more than one dot, but not consecutive in the local and domain parts.

Let’s take a look at the code:

@Test
public void testRestrictDots() {
    emailAddress = "[email protected]";
    regexPattern = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@" 
        + "[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

9. OWASP Validation Regular Expression

This regular expression is provided by the OWASP validation regex repository to check the email validation:

^[a-zA-Z0-9_+&*-] + (?:\\.[a-zA-Z0-9_+&*-] + )*@(?:[a-zA-Z0-9-]+\\.) + [a-zA-Z]{2, 7}

This regex also supports the most validations in the standard email structure.

Let’s verify the email address by using the below code:

@Test
public void testOwaspValidation() {
    emailAddress = "[email protected]";
    regexPattern = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

10. Gmail Special Case for Emails

There’s one special case that applies only to the Gmail domain: it’s permission to use the character + character in the local part of the email. For the Gmail domain, the two email addresses [email protected] and [email protected] are the same.

Also, [email protected] is similar to [email protected].

We must implement a slightly different regex that will pass the email validation for this special case as well:

^(?=.{1,64}@)[A-Za-z0-9_-+]+(\\.[A-Za-z0-9_-+]+)*@[^-][A-Za-z0-9-+]+(\\.[A-Za-z0-9-+]+)*(\\.[A-Za-z]{2,})$

Let’s write an example to test this use case:

@Test
public void testGmailSpecialCase() {
    emailAddress = "[email protected]";
    regexPattern = "^(?=.{1,64}@)[A-Za-z0-9\\+_-]+(\\.[A-Za-z0-9\\+_-]+)*@" 
        + "[^-][A-Za-z0-9\\+-]+(\\.[A-Za-z0-9\\+-]+)*(\\.[A-Za-z]{2,})$";
    assertTrue(EmailValidation.patternMatches(emailAddress, regexPattern));
}

11. Apache Commons Validator for Email

The Apache Commons Validator is a validation package that contains standard validation rules. So by importing this package, we can apply email validation.

We can use the EmailValidator class to validate the email, which uses RFC 822 standards. This Validator contains a mixture of custom code and regular expressions to validate an email. It not only supports the special characters, but also supports the Unicode characters we’ve discussed.

Let’s add the commons-validator dependency in our project:

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.8</version>
</dependency>

Now we can validate email addresses using the below code:

@Test
public void testUsingEmailValidator() {
    emailAddress = "[email protected]";
    assertTrue(EmailValidator.getInstance()
      .isValid(emailAddress));
}

12. Which Regex Should I Use?

In this article, we’ve looked at a variety of solutions using regex for email address validation. Obviously, determining which solution we should use depends on how strict we want our validation to be, and our exact requirements.

For example, we can use the simple regex from section 3 if we just need a simple regex to check the presence of an @ symbol in an email. However, for more detailed validation, we can opt for the stricter regex solution from section 6 based on the RFC5322 standard.

Finally, if we’re dealing with Unicode characters in an email, we can go for the regex solution provided in section 5.

13. Conclusion

In this article, we learned various ways to validate email addresses in Java using regular expressions.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)