Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

masking of email address in java

Tags:

I am trying to mask email address with "*" but I am bad at regex.

input : [email protected]
output : nil********@gmail.com

My code is

String maskedEmail = email.replaceAll("(?<=.{3}).(?=[^@]*?.@)", "*");

but its giving me output nil*******[email protected] I am not getting whats getting wrong here. Why last character is not converted? Also can someone explain meaning all these regex

like image 831
nilesh Avatar asked Oct 13 '15 10:10

nilesh


People also ask

How do I mask an email address in Java?

Here is the regex demo (replace with * ). See another regex demo, replace with $1* . Here, [^@] matches any character that is not @ , so we do not match addresses like [email protected] . Only those emails will be masked that have 4+ characters in the username part.

What is masking in Java?

Data masking is a method of creating a structurally similar version of an organization´s data that can be used for purposes such as software testing and user training. The purpose of data masking is to protect the actual data while having a functional substitute when the real data is not required.

What does email masking mean?

Email masking is a technique that alters an email address to protect the actual email from misuse. Email masking can help protect an organization's email address and that of thousands of its customers. A masked email address retains its original format and cannot be traced back to the actual address.


1 Answers

Your look-ahead (?=[^@]*?.@) requires at least 1 character to be there in front of @ (see the dot before @).

If you remove it, you will get all the expected symbols replaced:

(?<=.{3}).(?=[^@]*?@)

Here is the regex demo (replace with *).

However, the regex is not a proper regex for the task. You need a regex that will match each character after the first 3 characters up to the first @:

(^[^@]{3}|(?!^)\G)[^@]

See another regex demo, replace with $1*. Here, [^@] matches any character that is not @, so we do not match addresses like [email protected]. Only those emails will be masked that have 4+ characters in the username part.

See IDEONE demo:

String s = "[email protected]";
System.out.println(s.replaceAll("(^[^@]{3}|(?!^)\\G)[^@]", "$1*"));
like image 82
Wiktor Stribiżew Avatar answered Sep 20 '22 10:09

Wiktor Stribiżew