I need to mask a phone number
90 511 619 11 21
like this
5**6**1*2*
first I'm checking if it contains 90 (country code) and removing it
if (number.length() > 2 && number.substring(0,2).contains("90")){
number = number.replaceAll(number.substring(0,2), "");
}
then I'm removing all the spaces but I'm stuck at the regex part.
number = number.replaceAll(" ", "").replaceAll("\\d(?=\\d{4})", "*");
We can solve this problem without using any capture groups:
String input = "533 619 11 21";
input = input.replaceAll("(?<=\\d)\\d", "*").replaceAll(" ", "");
System.out.println(input);
5**6**1*2*
The replacement logic here is that any single digit which is immediately preceded by a digit gets replaced with asterisk. This of course spares the first digit.
Note that I assume that you already have some means to remove the country code.
\d(?<=\d{2})
Regex101 Demo
For your code, replace the space after *:
number = number.replaceAll("\\d(?<=\\d{2})", "*").replaceAll(" ", "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With