-1

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.

Regular expression for email masking

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Regex cannot count so getting the correct number of asterisks is impossible without additional processing. – MonkeyZeus Dec 24 '19 at 18:52
  • 1
    Thanks for your reply.Can you please guide me to do the additional processing? –  Dec 24 '19 at 19:02
  • Could further think of replacing all [`(?<!@|^)[^@\s](?!@|\w*$)` with `*`](https://regex101.com/r/A6rSQu/1) but not sure if this is a good idea :) As a Java String: `"(?<!@|^)[^@\\s](?!@|\\w*$)"` – bobble bubble Dec 24 '19 at 19:59

3 Answers3

2
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"
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Adwait Kumar
  • 1,552
  • 10
  • 25
2

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Nice on, albeit: this might be much easier to do "manually" by using string length and indexOf and so on. – GhostCat Dec 24 '19 at 19:23
0

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());
Bentaye
  • 9,403
  • 5
  • 32
  • 45