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.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.regex; public class RegExReplaceBackslash { public static void main(String[] args) { String str = "Hello\\ world"; str = str.replace("\\", ""); System.out.println(str); } } |
Output
1 |
Hello world |
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.
1 2 3 4 |
String str = "Hello\\ world\\"; str = str.replace("\\", ""); System.out.println(str); |
Output
1 |
Hello world |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.regex; public class RegExReplaceBackslash { public static void main(String[] args) { String str = "Hello\\ world\\"; str = str.replaceAll("\\\\", ""); System.out.println(str); } } |
Output
1 |
Hello world |
If you try to specify the backslash as “\\” inside the replaceAll
method, it will throw an exception.
1 2 3 4 |
String str = "Hello\\ world\\"; str = str.replaceAll("\\", ""); System.out.println(str); |
Output
1 2 3 4 5 6 7 8 |
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ at java.util.regex.Pattern.error(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.<init>(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.lang.String.replaceAll(Unknown Source) at com.javacodeexamples.regex.RegExReplaceBackslash.main(RegExReplaceBackslash.java:9) |
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.