Thursday, June 7, 2012

Replacing backslashes with something else in Java

The use of regular expression implemented in Java is messy when it comes to replacing '\' with something else. I have come across with a handy code example that shows how it could be done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class DoubleTheBackslash {
   public static void main(String[] args) {
      String[] inputs = {"abc\\\\def", "abc\\def\\\\ghi"};
       
      showReplacements(inputs, "(?<!\\\\)\\\\(?!\\\\)", "\\\\\\\\");
      showReplacements(inputs, "(?<!\\\\)\\\\(?!\\\\)", "$0$0");
      showReplacements(inputs, "([^\\\\])(\\\\)([^\\\\])", "$1\\\\\\\\$3");
      showReplacements(inputs, "([^\\\\])(\\\\)([^\\\\])", "$1$2$2$3");
   }
    
   private static void showReplacements(String[] inputs,
         String regex, String replaceWith) {
      for (String input : inputs) {
         System.out.println(input);
         System.out.println(input.replaceAll(regex, replaceWith));
         System.out.println();
      }
   }
}

No comments:

Post a Comment