rust 26 lines · 6 steps

Redacting emails in a file with Rust

A function that reads a file, replaces every email's local part with [REDACTED], and rewrites the file in place.

Explained by highlit
1use std::fs;
2use std::path::Path;
3 
4use regex::Regex;
5 
6pub fn redact_emails<P: AsRef<Path>>(path: P) -> std::io::Result<usize> {
7 let path = path.as_ref();
8 let contents = fs::read_to_string(path)?;
9 
10 let email = Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
11 .expect("invalid email pattern");
12 
13 let mut count = 0;
14 let redacted = email.replace_all(&contents, |caps: &regex::Captures| {
15 count += 1;
16 let matched = &caps[0];
17 let domain = matched.split('@').nth(1).unwrap_or("");
18 format!("[REDACTED]@{domain}")
19 });
20 
21 if count > 0 {
22 fs::write(path, redacted.as_ref())?;
23 }
24 
25 Ok(count)
26}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A closure passed to replace_all can carry mutable state, letting you count matches while you transform them.
  2. 2Returning io::Result and using the ? operator lets read and write errors propagate cleanly to the caller.
  3. 3Skipping the write when nothing matched avoids needless disk churn and preserves the file's timestamp.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Redacting emails in a file with Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code