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 ***.
Here is a simple solution using String#repeat(int) available as of java-11. 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)
null (return null / throw the NPE / throw a custom exception...)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With