Reputation: 161
I am having an issue with Groovy replace all. can someone suggest? I wanted to replace \
with /
.
String path= 'C:\path\of\my\file' // <- This path comes in dynamic, so I cannot have \\
path = path.replaceAll('\', '/')
println(path)
Upvotes: 0
Views: 75
Reputation: 27255
You could do this:
// If the value is coming in dynamically the `\\` won't
// be in the value, but if you want to represent a \ in source code
// like this it needs to be escaped.
String path= 'C:\\path\\of\\my\\file'
path = path.replaceAll('\\\\', '/')
println(path)
EDIT:
I have created a runnable example that demonstrates pulling the values in dynamically.
See the project at github.com/jeffbrown/asmescaping.
lib/src/main/resources/info.txt
C:\path\of\my\file
C:\path2\of\my\file
C:\path3\of\my\file
lib/src/main/groovy/asmescaping/SomeClass.groovy
package asmescaping
class SomeClass {
static void main(String[] args) {
def inputStream = SomeClass.getResourceAsStream('/info.txt')
inputStream.eachLine { line ->
String path = line.replaceAll('\\\\', '/')
println "Path: $path"
}
}
}
That code appears to work:
~ $ git clone [email protected]:jeffbrown/asmescaping.git
Cloning into 'asmescaping'...
remote: Enumerating objects: 20, done.
remote: Counting objects: 100% (20/20), done.
remote: Compressing objects: 100% (14/14), done.
remote: Total 20 (delta 0), reused 20 (delta 0), pack-reused 0
Receiving objects: 100% (20/20), 58.33 KiB | 1.04 MiB/s, done.
~ $
~ $ cd asmescaping
asmescaping (main)$ ./gradlew lib:run
> Task :lib:run
Path: C:/path/of/my/file
Path: C:/path2/of/my/file
Path: C:/path3/of/my/file
Upvotes: 1