Masking phone number Java

16,099

Solution 1

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

Solution 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})", "*");

Solution 3

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
Share:
16,099
Cassie
Author by

Cassie

Data Engineer

Updated on August 06, 2022

Comments

  • Cassie
    Cassie almost 2 years

    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!