How to extract a file name from a path, replace whitespaces, and make it lowercase using RegEx in Java

1 Answer

0 votes
public class NormalizeFilename {
    public static void main(String[] args) {
        String filePath = "c:\\path\\to\\file\\WITH Whitespace1 and Whitespace2.java";
        
        String result = normalizeFilename(filePath);
        
        System.out.println(result);
    }

    public static String normalizeFilename(String filePath) {
        // Extract only the file name
        String filename = filePath.replaceAll("^.*[\\\\/]([^\\\\/]*)$", "$1");

        // Replace whitespaces with underscores
        filename = filename.replaceAll("\\s", "_");

        // Convert to lowercase
        filename = filename.toLowerCase();

        return filename;
    }
}


 
/*
run:

with_whitespace1_and_whitespace2.java
 
*/

 



answered Jul 15, 2025 by avibootz
...