Warm tip: This article is reproduced from serverfault.com, please click

Mask some part of String

发布于 2014-07-17 05:54:59

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) test@mint.com - 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?

Questioner
Surendra Jnawali
Viewed
0
2,236 2014-12-08 19:16:09

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