Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Created November 24, 2024 12:10
Show Gist options
  • Save rochacbruno/6372f8f5719f5a300217131c63474403 to your computer and use it in GitHub Desktop.
Save rochacbruno/6372f8f5719f5a300217131c63474403 to your computer and use it in GitHub Desktop.
Remove date from filename Rust
use regex::Regex;
fn clean_filename(filename: &str) -> Option<String> {
// Regex to match the date/time prefix
let date_prefix_re = Regex::new(
r"^\d{4}-\d{2}-\d{2}([-T]\d{2}([:-]\d{2})?([:-]\d{2})?)?-",
)
.unwrap();
// Regex to remove the `.md` extension
let extension_re = Regex::new(r"\.md$").unwrap();
// Step 1: Remove the date/time prefix
let without_date = date_prefix_re.replace(filename, "").to_string();
// Step 2: Remove the `.md` extension
let cleaned = extension_re.replace(&without_date, "").to_string();
Some(cleaned)
}
fn main() {
let filenames = vec![
"my-file.md",
"2024-01-01-my-file-is-great.md",
"2024-01-01-15-30-my-file-is-awesome.md",
"2024-01-01-15-30-12-my-file-is-amazing-.md",
"2024-01-01T15:30-my-file-just.md",
"2024-01-01T15:30:12-myfile.md",
];
for filename in filenames {
match clean_filename(filename) {
Some(result) => println!("{} -> {}", filename, result),
None => println!("{} -> Invalid format", filename),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment