Regex to mask phone number in Java

I need to disguise a phone number

90 511 619 11 21

like this

5**6**1*2*

first i check if it contains 90 (country code) and delete it

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

then I remove all spaces, but I am stuck in the regex part.

number = number.replaceAll(" ", "").replaceAll("\\d(?=\\d{4})", "*");
+4
source share
4 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 that immediately precedes the digit is replaced with an asterisk. This, of course, takes the first digit.

Please note that I assume that you already have some means to delete the country code.

Demo

+6
source

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

Regex101 demo

For your code, replace the space after *:

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

+3
source

, :

^(?:90 *)?(\d)\d{2} *(\d)\d{2} *(\d)\d *(\d)\d$

:

$1**$2**$3*$4*

:

Regex 101 Demo

Java ( ):

final String regex = "^(?:90 *)?(\\d)\\d{2} *(\\d)\\d{2} *(\\d)\\d *(\\d)\\d$";
final String string = "90 533 619 11 21";
final String subst = "$1**$2**$3*$4*";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

final String result = matcher.replaceFirst(subst);
System.out.println(result);
+1

Try this regular expression on a line with 90 already deleted:

(?<! |^)\d

And replace with *. This gives5** 6** 1* 2*

This makes you look and claims that there is no place or beginning of the line, then it matches the number.

Then you can simply replace all spaces with empty lines to get 5**6**1*2*.

+1
source

Source: https://habr.com/ru/post/1693300/


All Articles