Reputation: 29
The requirement is as below:
Input: [email protected]
Output: r****i@*****.com
I tried below two regex's but I could not able to mask the gmail(domain name). Kindly help me on this.
String masked_email_Address2=email_Address.replaceAll("(?<=.{1}).(?=[^@]*?.@)", "*");
Output received as r****[email protected]
I searched in stack overflow on this, I got the below regex but it does not produce the correct result:
String masked_email_Address1=email_Address.replaceAll("\\b(\\w)[^@]+@\\S+(\\.[^\\s.]+)", "$1***@****$2");
Output received as: r***@****.com
-- One star(*) is missed between R&@.
Upvotes: 2
Views: 3466
Reputation: 737
Try this:
int idx = email_Address.indexOf('@');
String part1 = email_Address.substring(1, idx-1).replaceAll(".", "\\*");
String part2 = email_Address.substring(idx + 1, email_Address.lastIndexOf('.')).replaceAll(".", "\\*");
String masked_email_Address1=email_Address.replaceAll("^(\\S)[^@]+(\\S)@.*(\\..*)", "$1"+ part1 + "$2@" + part2 + "$3");
Upvotes: 0
Reputation: 10964
How about:
String masked_email_Address2=email_Address.replaceAll("(.)?[^@]*([^@])@\\S+(\\.[^\\s.]+)?", "$1****$2@****$3");
This will work as long as your address is longer than 1 character long.
Upvotes: 0
Reputation: 520948
I started out trying to do this with a one-liner using String#replaceAll
as you were doing, but then gave up, because variable length lookbehinds are not supported, and I could not come up with a pattern which did not use them.
Instead, try just using a format pattern matcher:
String email = "[email protected]";
String pattern = "([^@]+)@(.*)\\.(.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(email);
if (m.find( )) {
StringBuilder sb = new StringBuilder("");
sb.append(m.group(1).charAt(0));
sb.append(m.group(1).substring(1).replaceAll(".", "*"));
sb.append("@");
sb.append(m.group(2).replaceAll(".", "*"));
sb.append(".").append(m.group(3));
System.out.println(sb);
}
This may look like a lot of code to do a relatively small formatting job on an email address. If you like, you may put this code into utility method, and then you can still get the masking effect with a single line of code, when you call the method.
Upvotes: 2