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.

Please share this post:
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 Replace Email Addresses with Asterisks(*) in a String – Java

  1. It’s actually a cool and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

  2. Greate article. Keep writing such kind of information on your site.
    Im really impressed by your blog.
    Hey there, You have performed a fantastic job. I will certainly digg it
    and in my opinion recommend to my friends. I’m confident
    they’ll be benefited from this web site.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

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

%d bloggers like this: