This will try to mask even if the character count before the @
is less than or equal to 3.
public static String maskEmail(String fieldValue) { if (StringUtils.isBlank(fieldValue)) { return ""; } int pos = fieldValue.indexOf('@'); if (pos == -1) { return "*".repeat(fieldValue.length()); } int chars = Math.min(pos-1, 3); String pattstr = "(^[^@]{%d}|(?!^)\\G)[^@]".formatted(chars); return fieldValue.replaceAll(pattstr, "$1*"); }