Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking phone number Java

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!

like image 626
Cassie Avatar asked Nov 21 '17 09:11

Cassie


People also ask

How do I mask a phone number?

The FCC mandated that all carriers in the United States make it possible for users to be able to block their number from appearing on caller IDs. So, to mask your phone number straight from your phone, follow these steps: Enter *67 before the entire number, then press the call button.

How do I mask an email address in Java?

Here is the regex demo (replace with * ). See another regex demo, replace with $1* . Here, [^@] matches any character that is not @ , so we do not match addresses like [email protected] . Only those emails will be masked that have 4+ characters in the username part.

How do you mask a string in Java?

If you want to mask all characters with another character in one fell swoop you can use the String#replaceAll(String regex, String replacement) method: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String).


2 Answers

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

like image 173
anubhava Avatar answered Oct 11 '22 23:10

anubhava


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})", "*");
like image 26
мυѕτавєւмo Avatar answered Oct 11 '22 22:10

мυѕτавєւмo