Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask some part of String

Tags:

java

regex

mask

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?

like image 863
Surendra Jnawali Avatar asked Jul 17 '14 05:07

Surendra Jnawali


People also ask

How to mask part of string in Java?

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.

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.


1 Answers

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

  • The \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
  • In the replacement, $1 and $2 contain the content matched by Groups 1 and 2

Explanation: Email

  • The \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
  • In the replacement, $1 and $2 contain the content matched by Groups 1 and 2
like image 132
zx81 Avatar answered Oct 04 '22 20:10

zx81