Search code examples
javaregexstringreplaceall

Masking part of the string with a regex


The idea is to mask a string like it's done with a credit cards. It can be done with this one line of code. And it works. However I can't find any straightforward explanations of the regex used in this case.

public class Solution {
    public static void main(String[] args) {

        String t1 = "518798673672531762319871";
        System.out.println(t1.replaceAll(".(?=.{4})", "*"));
    }
}

Output is: ********************9871


Solution

  • Explanation of regex:

    .(?=.{4})
    
    • .: Match any character
    • (?=: Start of a lookahead condition
      • .{4}: that asserts presence of 4 characters
    • ): End of the lookahead condition

    In simple words it matches any character in input that has 4 characters on right hand side of the current position.

    Replacement is "*" which means for each matched character in inout, replace by a single * character, thus replacing all the characters in credit card number except the last 4 characters when lookahead condition fails the match (since we won't have 4 characters ahead of current position).

    Read more on look arounds in regex