使用Java / Groovy替换字符串中的反斜杠 [英] Replace backslashes in a string using Java/Groovy

查看:2242
本文介绍了使用Java / Groovy替换字符串中的反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让一个简单的字符串替换为使用Groovy脚本工作。尝试了各种各样的东西,包括以各种方式转义字符串,但无法弄清楚。

  String file =C:\\ \\\\\\\\\\\\\\\\\\\\\\''''''''''
String afile = file.toString()println
original string:+ afile
afile.replace(\\\\\,/)
afile.replaceAll(\\\\\,/)println
替换字符串:+ afile

此代码的结果是:

 原始字符串:C:\Test\Test1\Test2\Test3\ 
替换字符串:C:\Test\Test1\ Test2\Test3\



--------------- -------------



受到悲伤启发的答案如下所示:

  //首先替换反斜杠
String afile = file.toString()。replaceAll(\\\\,/)
//然后,将反斜杠转换为正斜杠
String fixed = afile.replaceAll(//,/)


解决方案

replace 返回一个不同的字符串。在Java中 String s不能被修改,所以你需要将替换结果赋给某个东西,并将其打印出来。

  String other = afile.replaceAll(\\\\,/)
println替换字符串:+ other

编辑:Neftas在评论中指出, \ 是一个正则表达式中的特殊字符,因此必须两次转义。


Trying to get a simple string replace to work using a Groovy script. Tried various things, including escaping strings in various ways, but can't figure it out.

String file ="C:\\Test\\Test1\\Test2\\Test3\\"
String afile = file.toString() println
"original string: " + afile
afile.replace("\\\\", "/")
afile.replaceAll("\\\\", "/") println
"replaced string: " + afile

This code results in:

original string: C:\Test\Test1\Test2\Test3\
replaced string: C:\Test\Test1\Test2\Test3\

----------------------------

The answer, as inspired by Sorrow, looks like this:

  // first, replace backslashes
  String afile = file.toString().replaceAll("\\\\", "/")
  // then, convert backslash to forward slash
  String fixed = afile.replaceAll("//", "/")  

解决方案

replace returns a different string. In Java Strings cannot be modified, so you need to assign the result of replacing to something, and print that out.

String other = afile.replaceAll("\\\\", "/")
println "replaced string: " + other

Edited: as Neftas pointed in the comment, \ is a special character in regex and thus have to be escaped twice.

这篇关于使用Java / Groovy替换字符串中的反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆