Utility Method to Replace Email Addresses with Asterisks(*) in a String – Java

Recently I came across a problem when I was needed to replace all email addresses in a String with asterisks(*). I have written a Utility Method to Replace Email Addresses with Asterisks in a String in Java. That functions are the following.

public static String replaceEmailAddressWithStarsInString(String text) {
        String finalText = text;
        ArrayList<String> emails = getEmailAddressesInString(text);
        for (String email: emails) {
            finalText = finalText.replaceAll(email,GiveStars(email.length()));
        return finalText;

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

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

private static String GiveStars(int number) {
        return new String(new char[number]).replace("\0", "*");

This is how you can call this Utility method.

String finalString = replaceEmailAddressWithStarsInString(YOUR_STRING);

In the above methods, you can see a method getEmailAddressesInString(). It returns ArrayList of all email addresses in the String. If you want to understand the inner details of this Function, you can have look at the following article.

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

Don’t forget to add the following imports.

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

That’s it. Enjoy 🙂

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

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

3 thoughts on “Utility Method to Replace Email Addresses with Asterisks(*) in a String – Java

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.