24
votes

I want to use the following string literal inside my groovy program without having to escape the backslashes:

C:\dev\username

Here is what I have tried so far:

String (Single Quotes) & GStrings (Double Quotes)

def aString = 'C:\dev\username'
def aGString = "C:\dev\username"
  • Doesn't work because \ has special meaning and is used to escape other characters
  • I end up having to escape \ with another \
def s = 'C:\\dev\\username'

Slashy String & Dollar Slashy String

Works for some strings, like the following

def slashy = /C:\windows\system32/
def dollarSlashy = $/C:\windows\system32/$

But it interprets \u as having special meaning (the following don't work):

def s1 = /C:\dev\username/
def s2 = $/C:\dev\username/$
  • Groovy:Did not find four digit hex character code
1
You can't. `` had a special meaning in Java and groovy, so you would need to escape them. If it's a path for a for, you should be able to use forward slashes though - tim_yates
@tim_yates Why does def slashy = /C:\windows\system32/ seems to work then? - Mike R
It works to it thinks you're defining a Unicode char, as you have found - tim_yates
@MikeR '/.../' is short for "create me a pattern" so you might at the end of the day run in further/other problems. - cfrick
Alternate solution: Because in Windows / can be used instead of \ as a path separator, you can simply use def path = "C:/windows/system32/" - Mike Rosoft

1 Answers

12
votes

Wow, another gotcha with putting Windows files paths in slashy strings. Nice catch. The gotcha I've encountered before was including a trailing backslash on the path, e.g. /C:\path\/, which results in an unexpected char: 0xFFFF error.

Anyways, for the sake of an answer, given that Windows paths are case insensitive, why not exploit it for once?

def s = /C:\DEV\USERNAME/

The \u unicode character escape sequence is case sensitive.