Search code examples
javaregexreplaceall

Mask Phone number with brackets and spaces Java


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:

enter image description here

But my output actually looks like this:

enter image description here

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!


Solution

  • 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.