pub fn replace_all(
pattern: &str,
replacement: impl AsRef<str>,
subject: impl AsRef<str>,
) -> String {
match regex::Regex::new(pattern) {
Ok(re) => re
.replace_all(
subject.as_ref(),
braced_backreferences(replacement.as_ref()).as_str(),
)
.into_owned(),
Err(_) => subject.as_ref().to_string(),
}
}
fn braced_backreferences(replacement: &str) -> String {
let mut out = String::with_capacity(replacement.len());
let mut chars = replacement.chars().peekable();
while let Some(c) = chars.next() {
if c != '$' {
out.push(c);
continue;
}
if chars.peek() == Some(&'$') {
out.push('$');
out.push(chars.next().unwrap());
continue;
}
let mut digits = String::new();
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
digits.push(d);
chars.next();
} else {
break;
}
}
if digits.is_empty() {
out.push('$');
} else {
out.push_str("${");
out.push_str(&digits);
out.push('}');
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replaces_every_match_using_a_backreference_in_the_replacement() {
let out = replace_all(
r#"(^|["'(\s])\/storage"#,
"$1https://cdn.example.com/storage",
r#"<img src="/storage/x.png"> /storage/y.png"#,
);
assert_eq!(
out,
r#"<img src="https://cdn.example.com/storage/x.png"> https://cdn.example.com/storage/y.png"#
);
}
#[test]
fn a_backreference_immediately_followed_by_a_word_character_is_disambiguated() {
let out = replace_all("a(b)c", "$1https://x", "abc");
assert_eq!(out, "bhttps://x");
}
#[test]
fn a_literal_dollar_sign_escaped_as_dollar_dollar_passes_through() {
let out = replace_all("a", "$$5", "a");
assert_eq!(out, "$5");
}
#[test]
fn no_match_leaves_the_subject_unchanged() {
let out = replace_all("nope", "x", "hello world");
assert_eq!(out, "hello world");
}
#[test]
fn an_invalid_pattern_falls_back_to_the_subject_unchanged_instead_of_panicking() {
let out = replace_all("(unterminated", "x", "hello world");
assert_eq!(out, "hello world");
}
#[test]
fn accepts_both_owned_and_borrowed_replacement_and_subject() {
let owned_subject = String::from("a/storage/b");
let owned_replacement = String::from("x");
assert_eq!(
replace_all(r"/storage", &owned_replacement, &owned_subject),
"ax/b"
);
assert_eq!(replace_all(r"/storage", "x", "a/storage/b"), "ax/b");
}
}