0

I'm trying to figure out how to isolate all file extensions from a list of file names using regex and endsWith.

So as an example

input: file.txt, notepad.exe

output: txt, exe

What my idea is, is to use filter to get file names that endsWith("."_). But endsWith("."_) doesn't work. Any suggestions?

JakoSA12
  • 13
  • 1
  • 5
  • Please show the actual code you have tried, an mwe. Please provide the output of your code and explain how that differs to the output you would like. – w08r Sep 30 '20 at 19:17
  • https://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java – Clashsoft Sep 30 '20 at 19:25

2 Answers2

1

You really do not want to filter, you want to map each filename into its extension.
(and maybe then collect only the ones that had an extension and probably you only want each unique extension)

You can use a regex for that.

object ExtExtractor {
  val ExtRegex = """.*\.(\w+)?""".r
  
  def apply(data: List[String]): Set[String] =
    data.iterator.collect {
      case ExtRegex(ext) => ext.toLowerCase
    }.toSet
}

You can see it running here.

-1

how about using split('.') which will return a

String[] parts = fileName.split("\\.");
String extension = parts[parts.length-1];
maxkart
  • 619
  • 5
  • 21
  • 1
    this does not work at all, see https://stackoverflow.com/questions/3387622/split-string-with-dot-as-delimiter. also the second line will throw an ArrayIndexOutOfBoundsException. – Clashsoft Sep 30 '20 at 19:24
  • Yup i see.. the array out of bound it would have to be length -1 – maxkart Sep 30 '20 at 20:00