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
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 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.