Search code examples
javaregexstringreplaceall

ReplaceAll with defined replacement number Java


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.


Solution

  • 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);
    }