I am trying to write a regular expression to mask an email address. Example below.
Input
john.doe@example.en.com
Output
j******e@e*********.com
Any help would be highly appreciated.
I tried from below link but could not changed it.
I am trying to write a regular expression to mask an email address. Example below.
Input
john.doe@example.en.com
Output
j******e@e*********.com
Any help would be highly appreciated.
I tried from below link but could not changed it.
s.replaceAll("(?<=.)[^@\n](?=[^@\n]*?[^@\n]@)|(?:(?<=@.)|(?!^)\\G(?=[^@\n]*$)).(?=.*[^@\n]\\.)","*")
https://regex101.com/r/gpZZsL/2
Tried on jshell
jshell> var s = "john.doe@example.en.com"
s ==> "john.doe@example.en.com"
jshell> s.replaceAll("(?<=.)[^@\n](?=[^@\n]*?[^@\n]@)|(?:(?<=@.)|(?!^)\\G(?=[^@\n]*$)).(?=.*[^@\n]\\.)","*")
$9 ==> "j******e@e********n.com"
You can use Pattern and Matcher with this regex (.)(.*?)(.@.)(.*?)(\.[^\.]+)$
which match many groups like so :
String email = "john.doe@example.en.com";
Pattern pattern = Pattern.compile("(.)(.*?)(.@.)(.*?)(\\.[^\\.]+)$");
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
email = matcher.group(1) + matcher.group(2).replaceAll(".", "*") +
matcher.group(3) + matcher.group(4).replaceAll(".", "*") +
matcher.group(5);
}
Output
j******e@e*********.com
Is a regex a requirement? ¯(°_o)/¯
You could also do it that way:
int atIndex = email.indexOf("@");
int lastDotIndex = email.lastIndexOf(".");
String maskedEmail = IntStream.range(0, email.length())
.boxed()
.map(i -> i==0 || (i>=atIndex-1 && i<=atIndex+1) || i>=lastDotIndex ?
email.charAt(i) : '*')
.map(String::valueOf)
.collect(Collectors.joining());