nessa/algorithms/
regex_ext.rs

1use regex::{Captures, Regex};
2
3// Taken from regex's docs
4pub fn replace_all_fallible<E>(
5    re: &Regex,
6    haystack: &str,
7    replacement: impl Fn(&Captures) -> Result<String, E>,
8) -> Result<String, E> {
9    let mut new = String::with_capacity(haystack.len());
10    let mut last_match = 0;
11    for caps in re.captures_iter(haystack) {
12        let m = caps.get(0).unwrap();
13        new.push_str(&haystack[last_match..m.start()]);
14        new.push_str(&replacement(&caps)?);
15        last_match = m.end();
16    }
17    new.push_str(&haystack[last_match..]);
18    Ok(new)
19}