Home > front end >  Replace phone numbers with asterisks pattern by Regex
Replace phone numbers with asterisks pattern by Regex

Time:11-22

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

The specification is the next:

Phone entry: (123) 123-12345

Output: (123) 12*-***45

Phone entry: (123) 123 12 12345

Output: (123) 12* ** ***45

I was trying with this pattern: (?<!\()\d(?!\d?$) and the replacing the matches with a "*"

But the final input is something like (123) 123-12345 -> (1**) ***-***45

CodePudding user response:

Using Java you can use a finite quantifier in a lookbehind assertion:

(?<=\)\h\d\d[\d\h-]{0,100})\d(?=[\h\d-]*\d\d$)

Explanation

  • (?<=\) Assert ) to the lelft
    • \h\d\d Match a space and 2 digits
    • [\d\h-]{0,100} Match 0-100 (100 is arbitrary but finite) digits, spaces or -
  • ) Close the lookbehind
  • \d Match a single digit (that will be replaced with *)
  • (?=[\h\d-]*\d\d$) Positive lookahead, assert optional digits, spaces or - to the right followed by 2 digits at the end of the string

See a regex demo and a Java demo.

In the replacement use a single asterix *

Example using Java

String regex = "(?<=\\) \\d\\d[\\d\\h-]{0,100})\\d(?=[\\h\\d-]*\\d\\d$)";
String string = " (123) 123-12345\n"
  • " (123) 123 12 12345";

    Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); Matcher matcher = pattern.matcher(string); String result = matcher.replaceAll("*");

    System.out.println(result);

Output

 (123) 12*-***45
 (123) 12* ** ***45
  • Related