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: ®ex::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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A closure passed to replace_all can carry mutable state, letting you count matches while you transform them.
- 2Returning io::Result and using the ? operator lets read and write errors propagate cleanly to the caller.
- 3Skipping the write when nothing matched avoids needless disk churn and preserves the file's timestamp.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/redacting-emails-in-a-file-with-rust-explained-rust-14eb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.