Regex replaces phone numbers with an asterisk

I want to apply a mask to my phone numbers, replacing some "*" characters.

The specification is as follows:

Phone Record : (123) 123-1234

Output : (1 **) *** - ** 34

I tried with this pattern: "\B\d(?=(?:\D*\d){2})"and replacing matches with "*"

But the final input is something like (123)465-7891 -> (1**)4**-7*91

Pretty similar to what I want, but with two extra matches. I was thinking of finding a way to use a zero match or once (??), but not sure how to do this.

+4
source share
4 answers

Try this regex:

(?<!\()\d(?!\d?$)

Replace each match with *

Click to demonstrate

Explanation:

  • (?<!\() - lookbehind, , (
  • \d -
  • (?!$) - lookahead, , ,
+5

:

  • \((\d)\d{2}\)\s+\d{3}-\d{2}(\d{2})
  • (\1**) ***-**\2

-, , . , .

Gurman my regex101 php engine, mine 14 , 80

+3

, , , , . : 12345678 : 1..4..7.

0

"":

function maskNumber(number){
    var getNumLength = number.length;
    // The number of asterisk, when added to 4 should correspond to length of the number
    var asteriskLength = getNumLength - 4;
    var maskNumber = number.substr(-4); 
    for (var i = 0; i < asteriskLength; i++) maskNumber+= '*';

    var mask = maskNumber.split(''), maskLength = mask.length;
    for(var i = maskLength - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = mask[i];
        mask[i] = mask[j];
        mask[j] = tmp;
    }

    return mask.join('');
}
-1

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


All Articles