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
source share