Scala expression to replace a file extension in a string

Will a simple regex replacement do the trick?

Like:

scala> "package.file.java".replaceAll("(\\.[^\\.]*$)", ".rb") 
scala> "package.file.rb"

I'm afraid you actually have to make it longer to do what is probably the most sensible robust thing:

scala> "oops".split('.').init ++ Seq("js") mkString "."  
res0: String = js

Kinda unexpected to lose the name of your file (at least if you're an end user)!

Let's try regex:

scala> "oops".replaceAll("\\.[^.]*$", ".js")
res1: java.lang.String = oops

Didn't lose the file name, but there's no extension either. Ack.

Let's fix it:

def extensor(orig: String, ext: String) = (orig.split('.') match {
  case xs @ Array(x) => xs
  case y => y.init
}) :+ "js" mkString "."

scala> extensor("oops","js")
res2: String = oops.js

scala> extensor("oops.txt","js")
res3: String = oops.js

scala> extensor("oops...um...","js")
res4: String = oops...js

Or with regex:

scala> "oops".replaceAll("\\.[^.]*$", "") + ".js" 
res5: java.lang.String = oops.js

scala> "oops.txt".replaceAll("\\.[^.]*$", "") + ".js"
res6: java.lang.String = oops.js

scala> "oops...um...".replaceAll("\\.[^.]*$", "") + ".js"
res7: java.lang.String = oops...um...js

(Note the different behavior on the corner case where the filename ends with periods.)

Tags:

Scala