groovy or java: how can replace '\' with '\\' 'C:\www\web-app\StudyReports\test.bat'
My eventual goal is to have a string like
def newline = 'C:\\www\web-app\StudyReports\\test.bat'
but my old line only has one '\'
.
I tried different ways of using the following:
def newline = oldline.replaceAll(/\\/,'//')开发者_高级运维
but that did not compile.
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.
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
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.
精彩评论