Reputation: 3099
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: [email protected]
. Output: s*****[email protected]
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.
Upvotes: 2
Views: 51
Reputation: 50716
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 @.
Upvotes: 3
Reputation: 21
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("[email protected]"));
//input : [email protected]
//output: s*****[email protected]
}
}
Upvotes: 2
Reputation: 311418
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);
}
Upvotes: 5