dja*_*fan 2 java string groovy
尝试使用Groovy脚本获取简单的字符串替换.试过各种各样的事情,包括以各种方式逃避字符串,但无法弄清楚.
String file ="C:\\Test\\Test1\\Test2\\Test3\\"
String afile = file.toString() println
"original string: " + afile
afile.replace("\\\\", "/")
afile.replaceAll("\\\\", "/") println
"replaced string: " + afile
Run Code Online (Sandbox Code Playgroud)
此代码导致:
original string: C:\Test\Test1\Test2\Test3\
replaced string: C:\Test\Test1\Test2\Test3\
Run Code Online (Sandbox Code Playgroud)
得到Sorrow的启发,答案如下:
// first, replace backslashes
String afile = file.toString().replaceAll("\\\\", "/")
// then, convert backslash to forward slash
String fixed = afile.replaceAll("//", "/")
Run Code Online (Sandbox Code Playgroud)
replace返回不同的字符串.在Java String中无法修改,因此您需要将替换结果分配给某些内容,然后将其打印出来.
String other = afile.replaceAll("\\\\", "/")
println "replaced string: " + other
Run Code Online (Sandbox Code Playgroud)
编辑:正如Neftas在评论中指出的那样,\是正则表达式中的一个特殊字符,因此必须两次转义.
在 Groovy 中,您甚至无法编写\\- 它是“不受支持的转义序列”。所以,我在这里看到的所有答案都是不正确的。
如果你的意思是一个反斜杠,你应该写\\\\. 因此,将反斜杠更改为普通斜杠将如下所示:
scriptPath = scriptPath.replaceAll("\\\\", "/")
Run Code Online (Sandbox Code Playgroud)
如果要替换成对反斜杠,则应加倍努力:
scriptPath = scriptPath.replaceAll("\\\\\\\\", "/")
Run Code Online (Sandbox Code Playgroud)
这些行在我刚刚再次有意启动的 Gradle/Groovy 脚本中成功使用 - 只是为了确定。
更有趣的是,为了在 StackOverflow 上的正常文本中显示这八个必要的反斜杠“\\\\\\\\”,我必须使用其中的 16 个!抱歉,我不会向您展示这 16 个,因为我需要 32 个!而且它永远不会结束......
| 归档时间: |
|
| 查看次数: |
22676 次 |
| 最近记录: |