Replace “ with \”

前端 未结 3 918
滥情空心
滥情空心 2020-12-30 10:02

How do I replace \" with \\\".

Here is what im trying :

def main(args:Array[String]) = {      
  val line:String = \"replace \\\" quote\";
  println         


        
相关标签:
3条回答
  • 2020-12-30 10:20

    Use "replaceAllLiterally" method of StringOps class. This replaces all literal occurrences of the argument:

    scala> val line:String = "replace \" quote"
    line: String = replace " quote
    
    scala> line.replaceAllLiterally("\"", "\\\"")
    res8: String = replace \" quote
    
    0 讨论(0)
  • 2020-12-30 10:23

    @pedrofurla nicely explains why you saw the behavior you did. Another solution to your problem would be to use a raw string with scala's triple-quote character. Anything between a pair of triple-quotes is treated as a raw string with no interpretation by the Scala compiler. Thus:

    scala> line.replaceAll("\"", """\\"""")
    res1: String = replace \" quote
    

    Used in conjunction with stripMargin, triple-quotes are a powerful way to embed raw strings into your code. For example:

    val foo = """
            |hocus
            |pocus""".stripMargin
    

    yields the string: "\nhocus\npocus"

    0 讨论(0)
  • 2020-12-30 10:27

    Two more \\ does the job:

    scala>  line.replaceAll("\"" , "\\\\\"");
    res5: java.lang.String = replace \" quote
    

    The problem here is that there are two 'layers' escaping the strings. The first layer is the compiler, which we can easily see in the REPL:

    scala> "\""
    res0: java.lang.String = "
    
    scala> "\\"
    res1: java.lang.String = \
    
    scala> "\\\""
    res2: java.lang.String = \"
    
    scala> val line:String = "replace \" quote";
    line: String = replace " quote
    

    The second layer is the regular expression interpreter. This one is harder to see, but can be seen by applyin your example:

    scala>  line.replaceAll("\"" , "\\\"");
    res5: java.lang.String = replace " quote
    

    What the reg. exp. interpreter really receives is \", which is interpreted as only ". So, we need the reg. exp. to receive \\". To make the compiler give us \ we need to write \\.

    Let's see the unescaping:

    • The right case: \\\" the compiler sees \", the regular expression sees \".
    • The wrong case: \\" the compiler sees \", the regular expression sees ".

    It can be a bit confusing despite being very straight forward.

    As pointed by @sschaef, another alternative it to use """ triple-quoting, strings in this form aren't unescaped by the compiler:

    scala>  line.replaceAll("\"" , """\\"""");
    res6: java.lang.String = replace \" quote
    
    0 讨论(0)
提交回复
热议问题