Reputation: 279
I'm trying to convert a string I dynamically get, to double the \ or convert them as / (both are ok for me).
It is formated as:
d:\code\main
I can't edit it at the source.
In my tests, I tried using replace or replaceAll function, with \ to 5 \\\, but I always run into this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
script15181726196231935876660.groovy: 4: unexpected char: '\' @ line 4, column 17.
String main = "d:\code\main\blabla\blabla"
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:302)
at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:149)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:119)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:131)
at org.codehaus.groovy.control.SourceUnit.addError(SourceUnit.java:359)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:137)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:108)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:236) ...
Is there a way convert or rebuild this variable without falling in this Java error ?
Thanks
Upvotes: 1
Views: 3622
Reputation: 2599
Dollar slashy string
and Slashy string
both allow backslashes.
def s1 = /d:\code/
def s2 = $/d:\code/$
s1.equals(s2) // true
The slashy string
has exactly one case where the backslash is a special symbol - if it comes before the forward slash:
def s3 = /This - \/ - is the forward slash/
// This - / - is the forward slash
Documentation can be found here.
Upvotes: 0
Reputation: 1471
The \
charactere is escape char https://en.wikipedia.org/wiki/Escape_character. So, to use it as a literal value use \\
instead.
String main = "d:\\code\\main\\blabla\\blabla"
Upvotes: 1