[英]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. Java和Windows都将正斜杠用作文件分隔符,并且使用起来要容易得多。
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. 要在Java或Groovy中匹配单个反斜杠,您必须输入4次,因为编译器和正则表达式引擎均使用反斜杠作为转义字符。 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 \\
. 因此,如果在Java中以字符串形式输入
"\\\\\\\\"
,则编译器将生成包含两个字符\\\\
的字符串,正则表达式引擎会将其解释为与一个反斜杠\\
完全匹配的字符。
The replacement string must be escaped twice too, so you have to enter 8 backslashes as the replacement string. 替换字符串也必须转义两次 ,因此您必须输入8个反斜杠作为替换字符串。
In Java, you'd use the String.replace(CharSequence target, CharSequence replacement)
, which is NOT regex-based. 在Java中,您可以使用
String.replace(CharSequence target, CharSequence replacement)
,它不是基于正则表达式的。
You'd write something like: 您将编写如下内容:
String after = before.replace("\\", "\\\\");
This doubles up every \\
in before
. 这双打每
\\
中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 ) 上面的输出是( 如ideone.com上所示 )
1\2\\3\4
1\\2\\\\3\\4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.