Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Remove or replace a backslash with replaceAll regex in Java

Sometimes logical solutions can be unintuitive. If you want to replace a single backslash in Java using replaceAll there are multiple layers of escaping that leads to four backslashes as an argument for replaceAll.

String bla = "blub\\"; 
//escape the backslash, otherwise this line would not compile

//output: blub\

String bla2 = bla.replaceAll("\\\\", "");
//first backslash: Java, escape the next character in String
//second backslash: Regex, escape the next character
//third backslash: Java, escape the next charcter in String
//fourth backslash: Regex, backslash that is to be replaced

//output: blub

This comment has been minimized.

Copy link

Edatokmakk commented Feb 27, 2019

Hey , how to delete everything from the double slash until the end of the line in java?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.