I have phone no and email address. I dont want to show full information.
So I am thinking mask some character using Regex or MaskFormatter.
Input and desired result
1) 9843444556 - 98*******6
2) [email protected] - t***@****.com
I have achieved this with String loop. But exactly I want to this by using regex or mask. Would you please kindly inform it?
String maskChar = "*"; //number of characters to be masked String maskString = StringUtils. repeat( maskChar, 4); //string to be masked String str = "FirstName"; //this will mask first 4 characters of the string System. out. println( StringUtils.
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.
Phone:
String replaced = yourString.replaceAll("\\b(\\d{2})\\d+(\\d)", "$1*******$2");
Email:
String replaced = yourString.replaceAll("\\b(\\w)[^@]+@\\S+(\\.[^\\s.]+)", "$1***@****$2");
Explanation: phone
\b
boundary helps check that we are the start of the digits (there are other ways to do this, but here this will do).(\d{2})
captures two digits to Group 1 (the two first digits)\d+
matches any number of digits(\d)
captures the final digit to Group 2$1
and $2
contain the content matched by Groups 1 and 2Explanation: Email
\b
boundary helps check that we are the start of the characters (there are other ways to do this, but here this will do).(\w)
captures one word char to Group 1[^@]+
matches one or more chars that are not @
\S+
matches one or more chars that are not whitespace chars(\.[^\s.]+)
captures a dot and any chars that are not a dot or space to Group 2$1
and $2
contain the content matched by Groups 1 and 2If 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