在字符串字面值中转义字符串内插。

huangapple go评论65阅读模式
英文:

Escape String interpolation in a string literal

问题

"在普通字符串中,我可以用反斜杠来转义${variable}

"你可以在Kotlin中使用${variable}语法。"

在字符串字面值中是否也可以这样做?反斜杠不再是转义字符:

// 不期望的结果:生成"This \something将被替换。
"""This ${variable}将被替换。"""

到目前为止,我看到的唯一解决方案是字符串连接,这实在太丑陋了,还有嵌套插值,这开始变得有点荒谬:

// 期望的结果:生成"This ${variable}不会被替换。"
"""This ${"${variable}"}不会被替换。"""
英文:

In a normal String I can escape the ${variable} with a backslash:

"You can use ${variable} syntax in Kotlin."

Is it possible to do the same in a String literal? The backslash is no longer an escape character:

// Undesired: Produces "This \something will be substituted.
"""This ${variable} will be substituted."""

So far, the only solutions I see are String concatenation, which is terribly ugly, and nesting the interpolation, which starts to get a bit ridiculous:

// Desired: Produces "This ${variable} will not be substituted."
"""This ${"${variable}"} will not be substituted."""

答案1

得分: 6

kotlinlang.org

如果您需要在原始字符串(不支持反斜杠转义)中表示字面$字符,您可以使用以下语法:

val price = """
${'$'}9.99
"""

所以,在您的情况下:

"""This ${'$'}{variable} will not be substituted."""
英文:

From kotlinlang.org:

If you need to represent a literal $ character in a raw string (which doesn't
support backslash escaping), you can use the following syntax:

val price = """
${'$'}9.99
"""

So, in your case:

"""This ${'$'}{variable} will not be substituted."""

答案2

得分: 5

根据String templates docs,您可以直接在原始字符串中表示$

> 模板支持原始字符串和转义字符串中的使用。如果您需要在原始字符串中表示文字 $ 字符(它不支持反斜杠转义),您可以使用以下语法:

val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.
英文:

As per String templates docs you can represent the $ directly in a raw string:

> Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:

val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.

huangapple
  • 本文由 发表于 2020年1月3日 18:27:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定