1 stable release
Uses new Rust 2024
new 1.0.0 | May 21, 2025 |
---|
#702 in Text processing
8KB
89 lines
STReplace
STReplace is a tiny library for matching and replacing in strings and slices with user-defined functions.
It provides three extension functions to the &str type, for this purpose.
Benchmarks
On a very basic benchmark, based on the example in the section below:
- This crate performed 12.9x as fast as regex,
- 10.1x as fast as regex-lite,
- 3.5x as fast as lazy-regex,
- 1.17x as fast as onig,
- and 0.21x as fast as str.replace.
Examples
use streplace::{InProgressMatch, Match, MatchResult, Matchable};
fn main() {
let test = "this is a test string";
let new = test.match_and_replace(
|progress, index, character| match progress {
Some(InProgressMatch { start, value }) => {
if index - start >= 4 {
println!("end {start} {value} {character}");
MatchResult::End
} else if "test"
.chars()
.nth(index - start)
.is_some_and(|c| character == c)
{
println!("cont {start} {value}{character}");
MatchResult::Continue
} else {
println!("fail {start} {value} {character}");
MatchResult::Fail
}
}
None => {
if character == 't' {
println!("start {index} {character}");
MatchResult::Start
} else {
println!("none {index} {character}");
MatchResult::None
}
}
},
|Match { start, end, value }| format!("start:{start},end:{end},val:{value}"),
);
println!("{new}");
}