How to replace backslash in Java?

Using the following way, we can easily replace a backslash in Java. The replaceAll() method, as you know, takes two parameters out of which, the first one is the regular expression (aka regex) and the next one is the replacement. The important point you need to note is that a single \\ is substituted as single backslash i.e. we need to escape it. But even, if it is done in the replaceAll() method, we do not get the desired output. This is because, in a regular expression, a single you need to escape the backslash twice. You need to submit two backslashes for substituting a single backslash meaning you need to escape both backslashes. This is how we can do it.

class ReplaceBackslash
{
public static void main(String args[])
{
// Take input from command line
String st=args[0];

// If it doesn't contains \ do nothing.
if(!args[0].contains("\\")) return;

// The wrong way
// This is wrong because, \\ ofcourse
// substitutes a single slash, but here it
// is not. This raises a PatternSyntaxException
// st=st.replaceAll("\\","/");


// The backslash should be escaped twice in a regex
// The first parameter of replaceAll is the regex
st=st.replaceAll("\\\\","/");

// Print the modified string
System.out.println("The modified string is "+st);
}
}

If you like this post or found it helpful, feel free to share it. You might also like to know why main is public static void?


Posted by at on

Tags: Regular Expressions, String Handling,