This post will discuss how to remove extension from file name in Kotlin.

1. Using String.substring() function

A simple solution to extract the filename without extension using the substring() function. Its usage is demonstrated below, using the lastIndexOf() function to get the last index of the dot (.) in the filename.

Download Code

 
The filename may have no extension. To handle this case, we should check the return value of the lastIndexOf() function before calling the substring() function:

Download  Run Code

2. Using Regex

An alternative idea is to use the regular expression \.\w+$ which matches with the last dot and all the characters that follow it. The following solution uses the replaceAll() function that can accept a regular expression.

Download  Run Code

That’s all about removing extension from file name in Kotlin.