Grzesiek Chyla
Grzesiek Chyla

Reputation: 103

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

Upvotes: 1

Views: 2722

Answers (2)

Caius Jard
Caius Jard

Reputation: 74605

?=.{4} is a positive lookahead. it matches the pattern inside the brackets (the next 4 digits after the current character) without including it in the main result (the . outside the brackets) that is matching all the other characters for replacement by *

Conceive that your regex goes through the input char by char. On the first digit (5) it asks "is there a single char followed by 4 other chars? yes, ok.. replace [the 5] with *"

It repeats this until the 9 (4th from end, at which point the "is there another 4 characters after this?" question becomes "no" and the replacing stops

Upvotes: 2

anubhava
anubhava

Reputation: 785246

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

Upvotes: 3

Related Questions