Regular expression for email masking

北城余情 提交于 2019-12-03 08:51:19

Update with various masking email solutions

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

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

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

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

  • foo@bar.comf*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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!