Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for phone number masking in Java

Tags:

java

regex

I need to mask a phone number

90 511 619 11 21

like this

5**6**1*2*

first I'm checking if it contains 90 (country code) and removing it

if (number.length() > 2 && number.substring(0,2).contains("90")){
            number = number.replaceAll(number.substring(0,2), "");
        }

then I'm removing all the spaces but I'm stuck at the regex part.

number = number.replaceAll(" ", "").replaceAll("\\d(?=\\d{4})", "*");
like image 926
Ege Kuzubasioglu Avatar asked Dec 18 '22 01:12

Ege Kuzubasioglu


2 Answers

We can solve this problem without using any capture groups:

String input = "533 619 11 21";
input = input.replaceAll("(?<=\\d)\\d", "*").replaceAll(" ", "");
System.out.println(input);

5**6**1*2*

The replacement logic here is that any single digit which is immediately preceded by a digit gets replaced with asterisk. This of course spares the first digit.

Note that I assume that you already have some means to remove the country code.

Demo

like image 159
Tim Biegeleisen Avatar answered Jan 01 '23 15:01

Tim Biegeleisen


\d(?<=\d{2})

Regex101 Demo

For your code, replace the space after *:

number = number.replaceAll("\\d(?<=\\d{2})", "*").replaceAll(" ", "");

like image 36
Yung Avatar answered Jan 01 '23 15:01

Yung