Mask some part of String

Surendra Jnawali picture Surendra Jnawali · Jul 17, 2014 · Viewed 8.3k times · Source

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?

Answer

zx81 picture zx81 · Jul 17, 2014

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