0

生の String は次のように宣言できることを知っています。

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

また

val foo: String = raw"foo"

ただし、文字列型の val がある場合、どうすれば raw に変換できますか? 例えば:

// 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 */
}
4

1 に答える 1

1

あなたの単純なケースでは、これを行うことができます:

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

より一般的な解決策として、Apache commons でStringEscapeUtils.escapeJavaを使用します。

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

注:あなたのコードは実際には意味がありません。無効な Scala 構文であるという事実は別として、正規表現パターンは、 orではなくString toBeMatched string のみに一致するように設定されており、正規表現が何かをキャプチャしようとしている場合にのみ意味がありますが、そうではありません。"foo""foo\n""foo\\n"pattern(res)

たぶん (?!) 次のような意味でしたか?:

def regexFoo(toBeMatched: String) = {
  val pattern = """foo(.*)""".r
  val pattern(res) = toBeMatched.replace("\n", "\\n") 
}
regexFoo("foo\n")  //  "\\n"
于 2014-08-03T22:14:06.757 に答える