Skip to content

Split a string in java based on custom logic

I have a string

"target/abcd12345671.csv"

and I need to extract

"abcd12345671"

from the string using Java. Can anyone suggest me a clean way to extract this.

Answer

Core Java

String fileName = Paths.get("target/abcd12345671.csv").getFileName().toString();
fileName = filename.replaceFirst("[.][^.]+$", "")

Using apache commons

import org.apache.commons.io.FilenameUtils;
String fileName = Paths.get("target/abcd12345671.csv").getFileName().toString();
String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);