Considering a path such as
var dir = new File(“””c:\test\project1″””);
How do I easily in Scala escape/quote this so it can be used safely in regular expressions
val extractRelativePath = (dir.getAbsolutePath() + “””(.*)”””).r
I tried using
dir.getAbsolutePath().replaceAll(“\\”, “\\\\”);
but this does not work. as the following example shows
def main(args: Array[String]): Unit = {
var base = new File("""c:\test\project1""");
val extractRelativePath = (base.getAbsolutePath() + """(.*)""").r
var dir = new File("""c:\test\project1\somedir""");
var extractRelativePath(rel) = dir.getAbsolutePath().replaceAll("\\\\", "\\\\")
}
Also is there not some standard functionality that does this safely across platforms like Pattern.quote ?.
You can use quotations, but I think that in your case you also need to escape
\E. Following code should do it:I generally replacing
\Ewith\E\\E\Q, so I split quotation and explicitly adding\\followed byEin regexp.Here is small example. If I have defined
baselike his:then it will produce following regexp:
As an advantage to this approach,
\Qand\Ewill escape everything and not only*or\.Here is the whole example code:
By the way
You can also use
Pattern.quotewhich makes exactly the same, but more efficiently: