How to insert double quotes into String with interpolation in scala

后端 未结 11 1564
北荒
北荒 2020-12-05 12:53

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)

相关标签:
11条回答
  • 2020-12-05 13:22

    How about

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

    0 讨论(0)
  • 2020-12-05 13:24

    This is a bug in 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
    
    0 讨论(0)
  • 2020-12-05 13:25

    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} ..."
    
    0 讨论(0)
  • 2020-12-05 13:25

    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"}
    
    0 讨论(0)
  • 2020-12-05 13:27

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

    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-24 for 2.12:

    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.

    0 讨论(0)
提交回复
热议问题