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
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.
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.
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.
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*"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With