Reputation: 1911
The scala StringContext has problems with invlaid escape characters. Example:
s"""v \C/R\ni"""
Raises "scala.StringContext$InvalidEscapeException: invalid escape character at index 2". http://www.scala-lang.org/api/current/index.html#scala.StringContext$$InvalidEscapeException
Is there an elegant and universal way to avoid this problem? Especially the valid escape characters should be preserved. Possible would be:
s"""v \\C/R\ni"""
Just for info: I'll pipe such strings into a scala interpreter, so it is possible to prepare the string.
At a pinch replace * with \* but not the ones from chapter 1.3.6 will do. Any clever ideas?
(I'm using scala 2.11.x)
Upvotes: 2
Views: 7898
Reputation: 1911
My solution at the moment:
val regex = "\\\\[^btnfr\"]".r
var str = """hi \C ho \t jo \n \" mu \M"""
val matches = regex.findAllIn(str).toList
val chars = matches.map(_(1))
for ( (x,y) <- matches zip chars) str = str.replace(x, "\\\\" + y)
The output is """hi \C ho \t jo \n \" mu \M""". Not very elegant, but it works. Maybe someone has an better, more "functional" solution?
Upvotes: 1