Skip to content

Java String Replace First N Characters

Java String replace first n characters example shows how to replace first n characters from string in Java using the substring method as well using a regex pattern.

How to replace first n characters in a string in Java?

Many times we want to replace the first few characters of a string with something else. For example, an app may need to display the first 4 characters of a number as “XXXX”.

There are a couple of ways using which we can do that. The first approach is to use the String substring method. We are going to use the overloaded version of the substring method that accepts the starting index.

This method returns the substring of the specified string starting from the specified index till the end of the string.

Once we get the substring from the 5th character onwards using the substring method, we are going to concat the replacement string with the substring as given in the below example.

Output

As you can see from the output, the first 4 characters of the string are replaced by the “*”.

Note: It is always best practice to check if the string length is more than 4 characters before getting the substring from index 4 to avoid StringIndexOutOfBoundsException exception.

How to get first n characters from a string using regex?

Instead of the substring method, we can also use the regex pattern along with the replaceAll method to replace the first few characters in the string. If we want to replace the first 5 characters, the pattern will be like given below.

Where,

Basically, this pattern will match the first 5 characters from the start of the string. When we use this pattern along with the replaceAll method, it replaces the first 5 characters with the given replacement string.

Here is the code example using this regex pattern.

Output

Are you looking for masking a string or masking a phone number?

If you want to learn more about the string, visit the Java String Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.