Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace backslashes in a string using Java/Groovy

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("//", "/")  
like image 654
djangofan Avatar asked Jun 16 '11 19:06

djangofan


People also ask

How do you replace a backslash in a string in Java?

replaceAll("\\/", "/");

How do you remove backslashes from string?

To remove all backslashes from a string: Call the replaceAll method, passing it a string containing 2 backslashes as the first parameter and an empty string as the second - str. replaceAll('\\', '') . The replaceAll method returns a new string with all of the matches replaced.

How do I replace a character in groovy?

Groovy - replaceAll() Replaces all occurrences of a captured group by the result of a closure on that text.

How do you remove a single backslash from a string in Java?

str = str. replace("\\", ""); replaceAll() treats the first argument as a regex, so you have to double escape the backslash. replace() treats it as a literal string, so you only have to escape it once.


1 Answers

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.

like image 159
Miki Avatar answered Sep 24 '22 08:09

Miki