Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for email masking

I am trying to write a regular expression to mask an email address. Example below.

input: [email protected]

output: j*******@e*********.com

I have tried the following but I just can't seem to get it working correctly.

regex:(?<=.).(?=[^@]\*?@)

output:j*******@example.en.com

regex:(?<=.).(?=[^@]\*?)(?=[^\.]\*?\.)

output:j******************.com

Any help would be appreciated. demo

like image 742
Randall Kwiatkowski Avatar asked Mar 24 '17 15:03

Randall Kwiatkowski


2 Answers

Update with various masking email solutions

  • [email protected]f**@b**.com (current question) - s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\\G(?=[^@]*$)).(?=.*\\.)", "*") (see the regex demo)

  • [email protected]f**@b*r.com - s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\\G(?=[^@]*$)).(?=.*[^@]\\.)", "*") (see the regex demo)

  • [email protected]f*o@b*r.com - s.replaceAll("(?<=.)[^@](?=[^@]*?[^@]@)|(?:(?<=@.)|(?!^)\\G(?=[^@]*$)).(?=.*[^@]\\.)", "*") (see the regex demo)

  • [email protected]f**@b*****m - s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\\G(?=[^@]*$)).(?!$)", "*") (see the regex demo)

  • [email protected]f*o@b*****m - s.replaceAll("(?<=.)[^@](?=[^@]*[^@]@)|(?:(?<=@.)|(?!^)\\G(?=[^@]*$)).(?!$)", "*") (see the regex demo)

Original answer

In case you can't use a code-based solution, you may use

s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\\G(?=[^@]*$)).(?=.*\\.)", "*")

See the regex demo

What it does:

  • (?<=.)[^@](?=[^@]*?@) -any char other than @ ([^@]) that is preceded by any single char ((?<=.)) and is followed with any 0 or more chars other than @ up to a @ ((?=[^@]*?@))
  • | - or
  • (?:(?<=@.)|(?!^)\\G(?=[^@]*$)) - match a location in the string that is preceded with @ and any char ((?<=@.)) or (|) the end of the previous successful match ((?!^)\\G) that is followed with any 0+ chars other than @ uo to the end of string ((?=[^@]*$))
  • . - any single char
  • (?=.*\\.) - followed with any 0+ chars up to the last . symbol in the string.
like image 86
Wiktor Stribiżew Avatar answered Sep 28 '22 18:09

Wiktor Stribiżew


How about this one if you do not need the masks having the same number of characters of the original strings (which is more anonymous):

(?<=^.)[^@]*|(?<=@.).*(?=\.[^.]+$)

For example, if you replace the matches with ***, the result would be:

j***@e***.com
like image 40
Chuancong Gao Avatar answered Sep 28 '22 19:09

Chuancong Gao