ReplaceAll with defined replacement number Java

Viewed 46

I have a method for email masking. I need to replace letters in the email before @ sign with stars. But the problem is that there is always should be exactly 5 stars and the first and last elements should not be hidden. A sample input would be: someemail@gmail.com. Output: s*****l@gmail.com So it does not matter how many characters between the first and the last one in the e-mail. Here is my code:

public static String maskEmail(String inputEmail){
    return inputEmail.replaceAll("(?<=.).(?=[^@]*?.@)", "*");
}

My method masks this e-mail, but the problem is that I don't know how to put 5 stars exactly.

3 Answers

It would be much simpler to just take the first letter and concatenate it with five asterisks and the substring starting from the letter before the @:

public static String maskEmail(String inputEmail) {
    return inputEmail.substring(0, 1) + 
           "*****" + 
           inputEmail.substring(inputEmail.indexOf('@') - 1);
}

How about this:

inputEmail.replaceAll("(?<=^.).*(?=.@)", "*****")

Or this:

inputEmail.replaceAll("(.).*(.@)", "$1*****$2")

Note that this only works if there are at least 2 characters before the @.

Try this code:

import java.util.Arrays;

public class HelloWorld{

    public static String StrToAsterisk(String email){
        if (email == null) return "";

        int flag = email.indexOf("@");
        if (flag < 0) return "";

        StringBuilder sb = new StringBuilder();
        sb.append(email.charAt(0));
        sb.append("*****");
        sb.append(email.substring(flag-1));
        return sb.toString();
     }

     public static void main(String []args){
         System.out.println(StrToAsterisk("someemail@gmail.com"));
         //input : someemail@gmail.com
         //output: s*****l@gmail.com
     }
 }
Related