Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to replace first 4 characters

Tags:

java

regex

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 ***.

like image 814
Aravind Av Avatar asked May 07 '26 03:05

Aravind Av


1 Answers

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)
  • 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.
like image 67
Nikolas Charalambidis Avatar answered May 09 '26 15:05

Nikolas Charalambidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!