Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: How can I include backslashes inside a string without escaping?

Tags:

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
like image 325
Mike R Avatar asked Nov 06 '14 21:11

Mike R


People also ask

How do you pass a backslash in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do you add double quotes to a string in Groovy?

replaceAll("\'", "\"") Will produce: ["one", "two", "three", "some \"other\""] . So quotes in values also replaced.


1 Answers

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.

like image 138
bdkosher Avatar answered Sep 20 '22 09:09

bdkosher