10

I need to mask the phone number. it may consist of the digits, + (for country code) and dashes. The country code may consist of 1 or more digits. I have created such kind of regular expression to mask all the digits except the last 4:

inputPhoneNum.replaceAll("\\d(?=\\d{4})", "*");

For such input: +13334445678

I get this result: +*******5678

However, it doesn't work for such input: +1-333-444-5678 In particular, it returns just the same number without any change. While the desired output is masking all the digits except for the last 4, plus sign and dashes. That is why I was wondering how I can change my regular expression to include dashes? I would be grateful for any help!

Cassie
  • 2,941
  • 8
  • 44
  • 92

6 Answers6

17

Use this regex for searching:

.(?=.{4})

RegEx Demo

Difference is that . will match any character not just a digit as in your regex.

Java code:

inputPhoneNum = inputPhoneNum.replaceAll(".(?=.{4})", "*");

However if your intent is to mask all digits before last 4 digits then use:

.(?=(?:\D*\d){4})

Or in Java:

inputPhoneNum = inputPhoneNum.replaceAll("\\d(?=(?:\\D*\\d){4})", "*");

(?=(?:\\D*\\d){4}) is a positive lookahead that asserts presence of at least 4 digits ahead that may be separated by 0 or more non-digits.

RegEx Demo 2

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • So `123-465-789` will mask everything but `-789` instead of "_all the digits except the last 4_" – AxelH Nov 21 '17 at 09:21
  • I don't know every phone format but it is probably valid somewhere ;) here we have a format like `0123-45-67-89`. – AxelH Nov 21 '17 at 09:24
  • You are still masking the initial `+` and all `-` in the number (though OP did not specify the correct behaviour for this). – Sebastian Proske Nov 21 '17 at 09:28
  • Yes because OP wrote: `While the desired output is masking all the digits except for the last 4, plus sign and dashes` – anubhava Nov 21 '17 at 09:29
  • 1
    I like that solution even if you just said that `+`, `-` and last 4 digit should still be visible ;) but I still like the solution. (and just need to replace `.` with `\d` to match that requirements) – AxelH Nov 21 '17 at 09:30
  • @anubhava I read that as _don't remove the last 4 digits, plus and dashes_, but might be wrong here. OPs sample at least shows that the plus should be left in place. – Sebastian Proske Nov 21 '17 at 09:32
  • Can you provide regex which keeps the area code and masks the rest ? – Anirudh Kashyap Dec 21 '17 at 01:01
  • @AnirudhKashyap Area code is not always 3 digits. You can do that using substring and replace as well. – anubhava Dec 21 '17 at 08:53
2

I'm not good in RegEx but I think you should normalize the phone numbers by getting rid of -occurences :

   inputPhoneNum = inputPhoneNum.replace("-","").replaceAll("\\d(?=\\d{4})", "*");
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21
  • You may remove hyphens without a regex, `.replaceAll("\\-","")` => `.replace("-","")`. BTW, there is no need escaping `-` in a regex when outside a character class. – Wiktor Stribiżew Nov 21 '17 at 09:24
  • @mustabelMo not really, not using a `Regex` is simpler/faster. – AxelH Nov 21 '17 at 09:26
2

Try to use two replace all non digit or + with empty then use your regex :

"+1-333-444-5678".replaceAll("[^\\d\\+]", "").replaceAll("\\d(?=\\d{4})", "*");

Output

+*******5678
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

I think this should work

".*\\d(?=\\d{4})","*"

You can try creating by hit and trial using this website.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
0

If you don't want to use regex, an alternate solution would be to loop through the String with a StringBuilder from end to start, and append the first 4 digits and then * after that (and just append any non-digit characters as normal)

public static String lastFour(String s) {
        StringBuilder lastFour = new StringBuilder();
        int check = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (Character.isDigit(s.charAt(i))) {
                check++;
            }
            if (check <= 4) {
                lastFour.append(s.charAt(i));
            } else {
                lastFour.append(Character.isDigit(s.charAt(i)) ? "*" : s.charAt(i));
            }
        }
        return lastFour.reverse().toString();
    }

Try it online!

achAmháin
  • 4,176
  • 4
  • 17
  • 40
0

This is what I used, it may be useful, just masks some digits in the provided number

 /*
 * mask mobile number .
 */
public  String maskMobileNumber(String mobile) {
    final String mask = "*******";
    mobile = mobile == null ? mask : mobile;
    final int lengthOfMobileNumber = mobile.length();
    if (lengthOfMobileNumber > 2) {
        final int maskLen = Math.min(Math.max(lengthOfMobileNumber / 2, 2), 6);
        final int start = (lengthOfMobileNumber - maskLen) / 2;
        return mobile.substring(0, start) + mask.substring(0, maskLen) + mobile.substring(start + maskLen);
    }
    return mobile;
}
Winter MC
  • 355
  • 2
  • 7