scala 如何在scala中使用插值将双引号插入到字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21086263/
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-10-22 05:59:37  来源:igfitidea点击:

How to insert double quotes into String with interpolation in scala

scalaintellij-idea

提问by Nimrod007

Having trouble escaping all the quotes in my function

无法转义函数中的所有引号

(basic usage of it -> if i find a string do nothing, if its not a string add " in the begin and end)

(它的基本用法 -> 如果我找到一个字符串,什么都不做,如果它不是一个字符串,在开头和结尾添加“)

code snippet :

代码片段:

  def putTheDoubleQuotes(value: Any): Any = {
    value match {
      case s: String => s //do something ...
      case _  => s"\"$value\"" //not working
    }
  }

only thing that worked was :

唯一有效的是:

case _ => s"""\"$value\""""

case _ => s"""\"$value\""""

is there a better syntax for this ?

有没有更好的语法?

it looks terrible and the IDE (IntelliJ) marks it in red (but lets you run it which really pisses me!!!!!)

它看起来很糟糕,IDE(IntelliJ)将它标记为红色(但让你运行它真的让我很生气!!!!!)

采纳答案by abzcoding

This is a bug in Scala:

这是 Scala 中的一个错误:

escape does not work with string interpolation

转义不适用于字符串插值

but maybe you can use:

但也许你可以使用:

scala> import org.apache.commons.lang.StringEscapeUtils.escapeJava
import org.apache.commons.lang.StringEscapeUtils.escapeJava

scala> escapeJava("this is a string\nover two lines")
res1: java.lang.String = this is a string\nover two lines

回答by Alexey Romanov

You don't need to escape quotes in triple-quoted string, so s""""$value"""""will work. Admittedly, it doesn't look good either.

您不需要在三引号字符串中转义引号,因此s""""$value"""""可以使用。不可否认,它看起来也不好看。

回答by Suma

Another solution (also mentioned in the Scala tracker) is to use

另一种解决方案(也在Scala 跟踪器中提到)是使用

case _ => s"${'"'}$value${'"'}"

Still ugly, but sometimes perhaps may be preferred over triple quotes.

仍然丑陋,但有时可能比三重引号更受欢迎。

It seems an escape sequence $"was suggested as a part of SIP-24for 2.12:

似乎$"有人建议将转义序列作为2.12的SIP-24的一部分:

case _ => s"$"$value$""

This SIP was never accepted, as it contained other more controversial suggestions. Currently there is an effort to get escape sequence $"implemented in 2.13 as Pre SIP/mini SIP $” escapes in interpolations.

这个 SIP 从未被接受,因为它包含其他更具争议的建议。目前正在努力$"在 2.13 中实现转义序列,因为Pre SIP/mini SIP $” 在插值中转义

回答by som-snytt

For your use case, they make it easy to achieve nice syntax.

对于您的用例,它们可以轻松实现良好的语法。

scala> implicit class `string quoter`(val sc: StringContext) {
     | def q(args: Any*): String = "\"" + sc.s(args: _*) + "\""
     | }
defined class string$u0020quoter

scala> q"hello,${" "*8}world"
res0: String = "hello,        world"

scala> "hello, world"
res1: String = hello, world       // REPL doesn't add the quotes, sanity check

scala> " hello, world "
res2: String = " hello, world "   // unless the string is untrimmed

Squirrel the implicit away in a package object somewhere.

将隐式隐藏在某个包对象中。

You can name the interpolator something besides q, of course.

q当然,除了 之外,您还可以命名插值器。

Last week, someone asked on the ML for the ability to use backquoted identifiers. Right now you can do res3 but not res4:

上周,有人在 ML 上询问是否可以使用反引号标识符。现在你可以做 res3 但不能做 res4:

scala> val `"` = "\""
": String = "

scala> s"${`"`}"
res3: String = "

scala> s"hello, so-called $`"`world$`"`"
res4: String = hello, so-called "world"

Another idea that just occurred to me was that the f-interpolator already does some work to massage your string. For instance, it has to handle "%n" intelligently. It could, at the same time, handle an additional escape "%q" which it would not pass through to the underlying formatter.

我刚刚想到的另一个想法是 f 插值器已经做了一些工作来按摩你的弦。例如,它必须智能地处理“%n”。同时,它可以处理一个额外的转义“%q”,它不会传递给底层格式化程序。

That would look like:

那看起来像:

scala> f"%qhello, world%q"
<console>:9: error: conversions must follow a splice; use %% for literal %, %n for newline

That's worth an enhancement request.

这值得一个增强请求。

Update: just noticed that octals aren't deprecated in interpolations yet:

更新:刚刚注意到八进制在插值中还没有被弃用:

scala> s"hello, world"
res12: String = "hello, world"

回答by NodeNodeNode

This fixed the problem for me, I tested this out and this is what I used.

这为我解决了问题,我对此进行了测试,这就是我使用的。

raw""" 
   Inside this block you can put "as many" quotes as you "want" and even "${5 + 7}" interpolate inside the quotes 
"""

http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-raw-interpolator

http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-raw-interpolator

回答by fwc

As already mentioned, this is a known bug in Scala. A workaround is to use \042.

如前所述,这是 Scala 中的一个已知错误。一种解决方法是使用\042.

回答by Venu Morigadi

Simple way:-

简单的方法:-

val str="abc"
println(s"$str") //without double quotes
println(s"""\"$str\"""") // with double quotes

回答by Naveen

How about

怎么样

s"This is ${"\"" + variable + "\""}" inserted in string with quotes

s"This is ${"\"" + variable + "\""}" inserted in string with quotes

回答by Pascalius

It's heavily used in my case, therefore I created this version:

它在我的情况下被大量使用,因此我创建了这个版本:

object StringUtil{
    implicit class StringImprovements(s: String) {
        def quoted = "\""+s+"\""
    }
}

val myStatement = s"INSERT INTO ${tableName.quoted} ..."

回答by R Sun

An example:

一个例子:

scala> val username="admin"
> username: String = admin

scala> val pass="xyz"
> pass: String = xyz

scala> println(s"""{"username":"$username", "pass":"$pass"}""")
> {"username":"admin", "pass":"xyz"}