Regex
Chester Wyke December 02, 2024 Updated: April 26, 2025 #Rust
Rust (Series)
Conditional Compilation
Install
Crate Serde
References
Cargo
Toolchain (Nightly)
String Formatting
Time
Crate Tokio
Publish Crate
rustfmt
Single file script
Snippets
CI
Pattern Type State
WASM
Create New Crate
Documentation
JSON
Pattern Builder
Testing
Working with collections of bytes
Thoughts about rust
Are we yet
OnceLock
Crate Actix Web
Stack Overflow
Crate Clap
Crate Poll Promise
Crate Insta
Tips
Create new egui project
Crate CSV
Crate egui
Iterators
Crate Tracing Subscriber
Regex
vscode
Enum Conversion
Macros
lettre
Google APIs
Conditional Compilation
Install
Crate Serde
References
Cargo
Toolchain (Nightly)
String Formatting
Time
Crate Tokio
Publish Crate
rustfmt
Single file script
Snippets
CI
Pattern Type State
WASM
Create New Crate
Documentation
JSON
Pattern Builder
Testing
Working with collections of bytes
Thoughts about rust
Are we yet
OnceLock
Crate Actix Web
Stack Overflow
Crate Clap
Crate Poll Promise
Crate Insta
Tips
Create new egui project
Crate CSV
Crate egui
Iterators
Crate Tracing Subscriber
Regex
vscode
Enum Conversion
Macros
lettre
Google APIs
Capture first match
NB: If regex is not executed more than once then you may opt to not use the Cells but they remove the need to recompile the regex.
Dependencies (anyhow is not needed by makes the code cleaner)
cargo add regex
cargo add anyhowuse anyhow::Context as _;
use regex::Regex;
use std::sync::OnceLock;
fn main() -> anyhow::Result<()> {
static CELL: OnceLock<Regex> = OnceLock::new();
let re = CELL.get_or_init(|| {
Regex::new(r"(\d+)").expect("failed to compile static regex that was known at design time")
});
let haystack = "There are 20 bad apples in the batch of 100";
let captures = re
.captures(haystack)
.with_context(|| format!("failed to find a match in: {haystack:?}"))?;
let number = captures
.get(1)
.with_context(|| format!("failed to extract number from: {haystack:?}"))?
.as_str();
// Prints: The number 20 was found in "There are 20 bad apples in the batch of 100"
println!("The number {number} was found in {haystack:?}");
Ok(())
}Capture all matches
See notes on Capture first match
cargo add regex
cargo add anyhowuse anyhow::Context as _;
use regex::Regex;
use std::sync::OnceLock;
fn main() -> anyhow::Result<()> {
static CELL: OnceLock<Regex> = OnceLock::new();
let re = CELL.get_or_init(|| {
Regex::new(r"(\d+)").expect("failed to compile static regex that was known at design time")
});
let haystack = "There are 20 bad apples in the batch of 100";
let captures_iter = re.captures_iter(haystack);
for captures in captures_iter {
let number = captures
.get(1)
.with_context(|| format!("failed to extract number from: {haystack:?}"))?
.as_str();
println!("A number {number} was found in {haystack:?}");
}
// Prints:
// A number 20 was found in "There are 20 bad apples in the batch of 100"
// A number 100 was found in "There are 20 bad apples in the batch of 100"
Ok(())
}