Regular expression to replace first 4 characters

Viewed 1636

I am trying to write a Regular Expression that replaces the first 4 characters of a string with *s

For example, for the 123456 input, the expected output is ****56.

If the input length is less than 4 then return only *s.

For example, if the input is 123, the return value must be ***.

3 Answers

Here is a simple solution using String#repeat(int) available as of . Regex is not needed.

static String hideFirst(String string, int size) {
    return size < string.length() ?                     // if string is longer than size
            "*".repeat(size) + string.substring(size) : // ... replace the part
            "*".repeat(string.length());                // ... or replace the whole
}
String s1 = hideFirst("123456789", 4);    // ****56789
String s2 = hideFirst("12345", 4);        // ****5
String s3 = hideFirst("1234", 4);         // ****
String s4 = hideFirst("123", 4);          // ***
String s5 = hideFirst("", 4);             // (empty string)
  • You might want to pass the asterisk (or any) character to the method for more control
  • You might want to handle null (return null / throw the NPE / throw a custom exception...)
  • For lower versions of Java, you need a different approach for the String repetition.

You can try the below regex to catch the first up to 4 characters.

(.{0,4})(.*)

Now, you can use Pattern, Matcher, and String classes to reach what you want.

Pattern pattern = Pattern.compile("(.{0,4})(.*)");
Matcher matcher = pattern.matcher("123456");

if (matcher.matches()) {
    String masked = matcher.group(1).replaceAll(".", "*");
    String result = matcher.replaceFirst(masked + "$2");

    System.out.println(result);
    // 123456 -> ****56
    // 123 -> ***
}

Simply use

String masked = string.replaceAll("(?<=^.{0,3}).", "*");

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    ^                        the beginning of the string
--------------------------------------------------------------------------------
    .{0,3}                   any character except \n (between 0 and 3
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  .                        any character except \n
Related