Jump to Real's How-to Main page

Replace a "\" by "\\"

It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\\\" in a regex expression.

So the regex expression to replace "\" to "\\" is

myString = myString.replaceAll("\\\\","\\\\\\\\");

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]