views:

714

answers:

2

Say I have something like this:

new File("test").eachFile() { file->  
println file.getName()  
}

This prints the full filename of every file in the test directory. Is there a Groovy way to get the filename without any extension? (Or am I back in regex land?)

+3  A: 

Maybe not as easy as you expected but working:

new File("test").eachFile { 
  println it.name.lastIndexOf('.') >= 0 ? 
     it.name[0 .. it.name.lastIndexOf('.')-1] : 
     it.name 
  }
alexander.egger
A: 

You can use regular expressions better. A function like the following would do the trick:

def getExtensionFromFilename(filename) {
  def returned_value = ""
  m = (filename =~ /(\.[^\.]*)$/)
  if (m.size()>0) returned_value = ((m[0][0].size()>0) ? m[0][0].substring(1).trim().toLowerCase() : "");
  return returned_value
}
Alex