Search code examples
regexscalarawstring

Scala convert a string to raw


I know raw String can be declared as:

val foo: String = """foo"""

or

val foo: String = raw"foo"

However, if I have a string type val, how can I convert it to raw? For example:

// val toBeMatched = "line1: foobarfoo\nline2: lol"
def regexFoo(toBeMatched: String) = {
     val pattern = "^.*foo[\\w+]foo.*$".r
     val pattern(res) = toBeMatched  /* <-- this line induces an exception 
       since Scala translates '\n' in string 'toBeMatched'. I want to convert
       toBeMatched to raw string before pattern matching */
}

Solution

  • In your simple case, you can do this:

    val a = "this\nthat"
    a.replace("\n", "\\n")  // this\nthat
    

    For a more general solution, use StringEscapeUtils.escapeJava in Apache commons.

    import org.apache.commons.lang3.StringEscapeUtils
    StringEscapeUtils.escapeJava("this\nthat")  // this\nthat
    

    Note: your code doesn't actually make any sense. Aside from the fact that String toBeMatched is invalid Scala syntax, your regex pattern is set up such that it will only match the string "foo", not "foo\n" or "foo\\n", and pattern(res) only makes sense if your regex is attempting to capture something, which it's not.

    Maybe (?!) you meant something like this?:

    def regexFoo(toBeMatched: String) = {
      val pattern = """foo(.*)""".r
      val pattern(res) = toBeMatched.replace("\n", "\\n") 
    }
    regexFoo("foo\n")  //  "\\n"