#testing #streplace #matchable

streplace

A tiny library for matching and replacing in strings and slices with user-defined functions

1 stable release

Uses new Rust 2024

new 1.0.0 May 21, 2025

#702 in Text processing

MIT-0 license

8KB
89 lines

STReplace

crates.io docs

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:

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}");
}

No runtime deps