tags:

views:

47

answers:

3

hi,

this might be trivial (please forgive me for that)

but my eventual goal is to have a string like

def newline= 'C:\\www\web-app\StudyReports\\test.bat'

but my old line only have one '\',

i tried different ways of using the following

def newline=oldline.replaceAll(/\\/,'//')

but did not work at ...

could someone help me out.

edit:

thank you all the excellent answers!!!

+1  A: 

To match a single backslash in Java or Groovy, you have to enter it 4 times, because both the compiler and the regex engine use the backslash as the escape character. So if you enter "\\\\" as a String in Java, the compiler generates the string containing the two characters \\, which the regex engine interprets as a match for exactly one backslash \.

The replacement string must be escaped twice too, so you have to enter 8 backslashes as the replacement string.

Christian Semrau
+1  A: 

In Java, you'd use the String.replace(CharSequence target, CharSequence replacement), which is NOT regex-based.

You'd write something like:

String after = before.replace("\\", "\\\\");

This doubles up every \ in before.

    String path = "1\\2\\\\3\\4";
    System.out.println(path);
    path = path.replace("\\", "\\\\");
    System.out.println(path);

The output of the above is (as seen on ideone.com)

1\2\\3\4
1\\2\\\\3\\4
polygenelubricants
A: 

If I were you, I would replace the backslashes with forward slashes:

def newline=oldline.replaceAll(/\\+/, '/')

Both Java and Windows will accept the forward slash as a file separator, and it's lot easier to work with.

Alan Moore