Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace phone numbers with asterisks pattern

Tags:

regex

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

The specification is the next:

Phone entry: (123) 123-1234

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

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

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

Pretty similar than I want but with two extra matches. I was thinking to find a way to use the match zero or once option (??) but not sure how.

like image 663
Luis Antoni Del Águila Jacobo Avatar asked Jan 29 '23 17:01

Luis Antoni Del Águila Jacobo


2 Answers

Try this Regex:

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

Replace each match with *

Click for Demo

Explanation:

  • (?<!\() - negative lookbehind to find the position which is not immediately preceded by (
  • \d - matches a digit
  • (?!$) - negative lookahead to find the position not immediately followed by an optional digit followed by end of the line
like image 81
Gurmanjot Singh Avatar answered Jan 31 '23 12:01

Gurmanjot Singh


Alternative without lookarounds :

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

In my opinion you should avoid lookarounds when possible. I find them less readable, they are less portable and often less performant.

Testing Gurman's regex and mine on regex101's php engine, mine completes in 14 steps while Gurman's completes in 80 steps

like image 44
Aaron Avatar answered Jan 31 '23 11:01

Aaron