Search code examples
scalatypesafe

How to replace \\ in a string with \ in scala?


I am trying to parse a file using typesafe config in scala. The file has key value pairs to be loaded as configurations in my application. The is key is a regex. Ex: "ASD\\.KL.*\\." = "somevalue"
The regex has to be loaded as "ASD\.KL.*\." It does not work with typesafe config factory but works with Properties Configuration. So Im trying to replace "ASD\\.KL.*\\.".replaceAll("\\\\","\\") but this doesnot work too. Any help appreciated.


Solution

  • Instead of trying to do a specific replace, you should use unescape the "raw" string to get respective Java/Scala String as it will take care of the "raw"-ness of any raw string and not just your special case.

    Add following dependency for commons-lang`,

    libraryDependencies += "commons-lang" % "commons-lang" % "2.6"
    

    Now, you can use StringEscapeUtils provided by commons-lang

    import org.apache.commons.lang.StringEscapeUtils
    
    val rawString = raw"ASD\\.KL.*\\."
    // rawString: String = ASD\\.KL.*\\.
    
    val requiredString = StringEscapeUtils.unescapeJava(rawString)
    // requiredString: String = ASD\.KL.*\.