This Kotlin tutorial shows you ways to get File Name from full path with Kotlin Regex and extension functions.
>>> Refer to: JavaSampleApproach.com
I. Technology
– Java 1.8
– Kotlin 1.1.2
II. Practice
1. Using Regex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.kotlination.filename fun main(args: Array<String>) { val fullPath = "Kotlination/Kotlin/Practice/getFileNameExample.kt" val regex = """(.+)/(.+)\.(.+)""".toRegex() val matchResult = regex.matchEntire(fullPath) if (matchResult != null) { val (directory, fileName, extension) = matchResult.destructured println("dir: $directory | fileName: $fileName | extension: $extension") } } |
Result:
1 |
dir: Kotlination/Kotlin/Practice | fileName: getFileNameExample | extension: kt |
2. Using Kotlin String extension function
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.kotlination.filename fun main(args: Array<String>) { val fullPath = "Kotlination/Kotlin/Practice/getFileNameExample.kt" val directory = fullPath.substringBeforeLast("/") val fullName = fullPath.substringAfterLast("/") val fileName = fullName.substringBeforeLast(".") val extension = fullName.substringAfterLast(".") println("dir: $directory | fileName: $fileName | extension: $extension") } |
Result:
1 |
dir: Kotlination/Kotlin/Practice | fileName: getFileNameExample | extension: kt |