Utility Method to Get All Email Addresses From a String in Java

Recently I came across a problem when I was needed to get ArrayList of all Email Addresses from a String in java. I’ve decided to write this article to share it with other developers. In this function java.util.regex.Matcher and java.util.regex.Pattern classes are used.

First, you need to know about the regular expression to match the pattern of email addresses. The regular expression is the following.


Add the following imports to use Java Matcher, Pattern & ArrayList classes.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;

Now we need to create a Pattern class object and initialize it with the above regular expression. Then call Pattern.matcher() method. This method returns a matcher object. As shown below.

Matcher matcher = Pattern.compile("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}").matcher(text);

Now we can iterate through the Matcher object by using matcher.find() method. It gives all the Strings matched with the pattern using matcher.group() method. As shown in the following code.

while (matcher.find()) {
           String email = matcher.group();

Full Method to get all Email Addresses from a String in Java

public static ArrayList<String> getEmailAddressesInString(String text) {
        ArrayList<String> emails = new ArrayList<>();

        Matcher matcher = Pattern.compile("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}").matcher(text);
       while (matcher.find()) {
        return emails;

You can use this method to find Strings of any pattern. You just need to change the above regular expression according to your requirements.

That’s it. Enjoy 🙂

If you are looking to replace Email Addresses with Asterisks(*) in a String have a look at this article.

Don’t forget to visit our Coding Articles & Tutorials Knowledge Base for other helping materials & code snippets.

Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

5 thoughts on “Utility Method to Get All Email Addresses From a String in Java

  1. I have recently started a website, the information you provide on this site has helped me tremendously. Thanks for all of your time & work. “A creative man is motivated by the desire to achieve, not by the desire to beat others.” by Ayn Rand.

  2. I keep listening to the news broadcast speak about receiving free online grant applications so I have been looking around for the finest site to get one. Could you advise me please, where could i find some?

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.