Regex for masking starting 8 characters of string

Viewed 225

I am trying to mask the starting exact 8 characters of a given string, which can contain any character and of any length, with below JAVA code.

String maskChar = "x";
String fieldName = "j@#G}3 2jklWEFSD681@#";
fieldName = fieldName.replaceAll("(?:^.{8})", maskChar);

is giving the output xjklWEFSD681@#, which is replaced with single 'x'.
But the EXPECTED OUTPUT should be xxxxxxxxjklWEFSD681@#.

This code have regex (?:^.{8}), which returns the complete & exact 8 starting characters as string, so when it is masking, it is replacing the returned string with single maskChar. And this should also handle the case when string length is less than 8 characters, where it should mask all the characters of the given string.

So the question is, how can I make the regex return in characters NOT as a string? or please suggest different regex which does, as I am new to this. Thanks.

1 Answers

You can use

fieldName = fieldName.replaceAll("(?<=^.{0,7}).", maskChar);

See the Java regex demo.

Details:

  • (?<=^.{0,7}) - a positive lookbehind that matches a position that is immediately preceded with zero to seven chars other than line break chars
  • . - any single char other than line break chars.
Related