如何在Scala的三引号字符串中包含 `"""`?

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

How do you include `"""` in a Scala triple-quoted string?

问题

这样奇怪,我找不到这个。如果你想在一个三重引号字符串中包含 """,你不能用 \" 替换其中一个 ",因为那会被解释为反斜杠 + 引号。

唯一的替代方式是将其中一个 " 替换为 \u0022 吗?

英文:

Weirdly, I can't find this. If you want to include """ in a triple-quoted string, you can't replace one of the "s with \", because that will be interpreted as backslash + quote.

Is the only way to replace one of the three with \u0022?

答案1

得分: 4

There's plenty of ways actually.

val q = '"'
println(s""""$q$q$q"""")
println(s""""""""""$q"""""") // this works too

Or

println("""""""""""")

The above prints three double-quotes ... but I don't think you can add much of anything else there. Can do this though

val q = """''''''''"""
println(s""""${q}foo bar${q}"""")

This prints """foo bar"""

Also, this: s""""${"\""*3}"""

Or this: s""""${'"'.toString * 3}"""

Or this: s""""${Seq.fill(3)('"').mkString}"""

英文:

There's plenty of ways actually.

val q = '"'
println(s"""$q$q$q""")
println(s"""""$q""") // this works too

Or

println(""""""""")

The above prints three double-quotes ... but I don't think you can add much of anything else there. Can do this though

val q = """""""""
println(s"""${q}foo bar${q}""")

This prints """foo bar"""

Also, this: s"${"\""*3}"

Or this: s"${'"'.toString * 3}"

Or this: s"${Seq.fill(3)('"').mkString}"

答案2

得分: 1

你可以尝试使用插值技巧:

val str = s"""
foo ${"\"\"\""} bar
"""

println(str) // 输出 'foo """ bar'

或者

val str = s"""
foo ${"""""""""} bar
"""
英文:

You can try interpolation trick:

val str = s"""
foo ${"\"\"\""} bar
"""

println(str) // prints 'foo """ bar'

Or

val str = s"""
foo ${"""""""""} bar
"""

huangapple
  • 本文由 发表于 2023年5月18日 04:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275987.html
匿名

发表评论

匿名网友

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

确定