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

1 Answer

0 votes
use regex::Regex;

fn normalize_filename(file_path: &str) -> String {
    // Extract the filename using regex
    let re = Regex::new(r"^.*[\\/](.*)$").unwrap();
    let filename = re
        .captures(file_path)
        .and_then(|caps| caps.get(1).map(|m| m.as_str()))
        .unwrap_or(file_path);

    // Replace whitespaces with underscores
    let filename = filename.replace(' ', "_");

    // Convert to lowercase
    filename.to_lowercase()
}

fn main() {
    let file_path = r"c:\path\to\file\WITH Whitespace1 and Whitespace2.rs";
    let result = normalize_filename(file_path);
    println!("{}", result); 
}

   
     
/*
run:

with_whitespace1_and_whitespace2.rs
   
*/
  
 

 



answered Jul 15, 2025 by avibootz
...