Mask part String

I do not have a phone or email address. I do not want to show full information.
So I think that mask some character using Regex or MaskFormatter.

Entrance and desired result

1) 9843444556 - 98*******6 2) test@mint.com - t***@****.com 

I achieved this with a String loop. But that is exactly what I want with a regular expression or mask. Could you report this?

+6
source share
1 answer

Telephone:

 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 border helps verify that we start numbers (there are other ways to do this, but here it will do).
  • (\d{2}) captures two digits for group 1 (two first digits)
  • \d+ matches any number of digits
  • (\d) captures the final digit for group 2
  • When replacing, $1 and $2 contain content matched by groups 1 and 2

Explanation: Email

  • The \b border helps verify that we are the beginning of characters (there are other ways to do this, but here it will do).
  • (\w) captures one char word for group 1
  • [^@]+ matches one or more characters that are not @
  • \S+ matches one or more characters that are not space characters
  • (\.[^\s.]+) fixes a point and any characters that are not a point or space for group 2
  • When replacing, $1 and $2 contain content matched by groups 1 and 2
+18
source

Source: https://habr.com/ru/post/972364/


All Articles