I have a method for the phone number masking. I need to replace all digits with stars except the last 4. Sample inputs would be: +91 (333) 444-5678 and +1(333) 456-7890. Outputs should look this way:

But my output actually looks like this:

So here is my code:
public static String maskPhoneNumber(String inputPhoneNum){
return inputPhoneNum.replaceAll("\\(", "-")
.replaceAll("\\)", "-")
.replaceAll(" ", "-")
.replaceAll("\\d(?=(?:\\D*\\d){4})", "*");
}
My method works with different number of digits in country codes, but it breaks in cases when instead of a space between digits there are brackets near the country code (triad after it). I would be grateful for some hints on how I can improve my approach!
Currently, you replace each individual space, ( and ) with a -. You need to replace all consecutive occurrences with 1 hyphen.
Use
public static String maskPhoneNumber(String inputPhoneNum){
return inputPhoneNum.replaceAll("[()\\s]+", "-")
.replaceAll("\\d(?=(?:\\D*\\d){4})", "*");
}
See this Java demo.
The +91 (333) 444-5678 turns into +**-***-***-5678 and +1(333) 456-7890 turns into +*-***-***-7890.
The [()\s]+ pattern matches 1 or more (+) consecutive (, ) or whitespace chars. See the "normalization" step regex demo and the final step demo.
There is a dedicated API in the language itself for that (in the form of appendReplacement)
String test = "+91 (333) 444-5678";
test = test.replaceAll("[()\\s]+", "-");
Pattern p = Pattern.compile("\\d+(?!\\d*$)");
Matcher m = p.matcher(test);
StringBuilder sb = new StringBuilder(); // +**-***-***-5678
for (; m.find();) {
m.appendReplacement(sb, m.group().replaceAll(".", "*"));
}
m.appendTail(sb);
System.out.println(sb.toString());
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