Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 898
Cassie Avatar asked Mar 27 '26 07:03

Cassie


2 Answers

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.

like image 152
Wiktor Stribiżew Avatar answered Mar 29 '26 19:03

Wiktor Stribiżew


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());
like image 22
Eugene Avatar answered Mar 29 '26 19:03

Eugene