Java RegEx – Mask Phone Numbers

Java RegEx – Mask Phone Numbers example shows how to mask phone numbers using regex in Java. It also shows how to mask starting few digits with the * (asterisk) of the phone numbers.

How to mask phone numbers using a regex pattern in Java?

In many use cases, we need to mask the first few digits of a phone number. For example, in many applications, phone numbers are displayed on the front-end with starting few digits marked as * in order to avoid misuse and protect the privacy of the customer.

Masking of phone number digits can be done using a regex pattern. We need to first determine how many digits we need to mask using the asterisk (*). Here is the regex pattern assuming that we want to display the last 3 digits out of 10. The rest of the digits need to be displayed as an *.

Where,

The positive lookahead expression looks for the given expression to the right side from the current position. In simple words, it is used when we want to search for something in a string followed by something else but do not want to include that something else in the match.

In the above pattern, we are matching a digit that is followed by exactly 3 digits in the string. For example, in a 10 digit number, it will match from the start of the string till the 7th digit. Because that is the last digit that is followed by 3 more digits.

Once we get that match, we will use the replaceAll method to replace all the matching digits with an asterisk character as given below.

Output

As you can see from the output, regardless of the length of the phone number, it always displays the last 3 digits of it. You can adjust the pattern to display n number of unmasked digits. For example, If you want to display the last 4 digits instead of 3, you can use a pattern like “\\d(?=\\d{4})”.

Important Note:

Before masking the phone number, replace all non-digit characters from the phone numbers like hyphens for the pattern to work properly. You can use “[^0-9]” to replace all non-digit characters. See below given example.

Output

If you want to learn more about the regex patterns, visit the Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *