string Groovy:如何在不转义的情况下在字符串中包含反斜杠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26790056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:18:39  来源:igfitidea点击:

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

stringgroovyscripting

提问by Mike R

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

我想在我的 groovy 程序中使用以下字符串文字而不必转义反斜杠:

C:\dev\username

Here is what I have tried so far:

这是我迄今为止尝试过的:

String (Single Quotes) & GStrings (Double Quotes)

字符串(单引号)和 GStrings(双引号)

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

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):

但它将 \u 解释为具有特殊含义(以下不起作用):

def s1 = /C:\dev\username/
def s2 = $/C:\dev\username/$
  • Groovy:Did not find four digit hex character code
  • Groovy:未找到四位十六进制字符代码

采纳答案by bdkosher

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: 0xFFFFerror.

哇,另一个将 Windows 文件路径放在斜线字符串中的问题。不错的收获。我之前遇到的问题是在路径上包含一个尾随反斜杠,例如/C:\path\/,会导致unexpected char: 0xFFFF错误。

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

无论如何,为了回答,鉴于 Windows 路径不区分大小写,为什么不利用它一次呢?

def s = /C:\DEV\USERNAME/

The \uunicode character escape sequence iscase sensitive.

\uUnicode字符转义序列区分大小写的。