Java RegEx – Replace Backslash

Java RegEx – replace backslash (\) example shows how to replace a backslash character from string in Java using the regular expression pattern.

How to replace a backslash from a string in Java?

Many a time we have a backslash character in our string content and either we want to remove it or replace it with something else. This can easily be done using the String replace method. The replace method accepts two arguments, the string we want to replace and the replacement string.

Since the backslash character in Java is used to escape other characters inside the string, we need to make it double backslash “\\” inside the replace method. Please see below given example to understand that.

Output

As you can see from the output, it removed the backslash from the string content.

Important Note:

Even though the method name is replace and we have another method called replaceAll, the replace method also replaces all occurrences of the string. The difference is the replaceAll method takes the regex pattern as a search string, while the replace method does not. See below given example.

Output

When it comes to the replaceAll method to replace the backslash, we need to make the search string as “\\\\”. The reason is, the regex pattern in Java is specified as a string so we have to double escape the backslash character as given in the below code example.

Output

If you try to specify the backslash as “\\” inside the replaceAll method, it will throw an exception.

Output

So in short, if you are using the replace method, use “\\” as the search string. If you are using the replaceAll method, use “\\\\” as a search string to replace the backslash.

If you want to learn more about regular expressions, please visit the Java regex tutorial.

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

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *