pub fn string_replace_all<'a, P: Into<Pattern<'a>>>(
input: &str,
pattern: P,
replacement: &str,
) -> String
Expand description
Replaces all occurrences of from
with to
in input
, supporting both exact string and regex replacements.
This function works as follows:
- If
from
is a string slice (&str
), it performs a simple.replace()
on the input. - If
from
is a regex (Regex
), it applies.replace_all()
to match the pattern. - The original input string remains unchanged and a new
String
is returned. - Consecutive occurrences of
to
are collapsed into a single instance to avoid unintended duplication.
§Arguments
input
- The original string.from
- The pattern to replace (either a string slice or a regex).to
- The replacement string.
§Returns
A new String
with all occurrences replaced. Consecutive duplicates of to
are merged.
§Examples
use string_replace_all::string_replace_all;
let text = "Hello world! This is Rust.";
let result = string_replace_all(text, "world", "RustLang");
assert_eq!(result, "Hello RustLang! This is Rust.");
use string_replace_all::string_replace_all;
let text = "A B C D";
let result = string_replace_all(text, "B", "X");
assert_eq!(result, "A X C D"); // Spaces are properly collapsed
use string_replace_all::string_replace_all;
let text = "Some special characters like * & % !";
let result = string_replace_all(text, "*", "[STAR]");
assert_eq!(result, "Some special characters like [STAR] & % !");
use regex::Regex;
use string_replace_all::string_replace_all;
let text = "I think Ruth's dog is cuter than your dog!";
let regex = Regex::new("(?i)Dog").unwrap(); // Case-insensitive regex
let result = string_replace_all(text, ®ex, "ferret");
assert_eq!(result, "I think Ruth's ferret is cuter than your ferret!");